Is there a way to automatically tie a UITextField to a variable in my data model?

五迷三道 提交于 2019-12-01 18:54:40

You can use UITextField+blocks it may be less entangled. And it will be much easier if objects have similar interface or implement one protocol with method like setText: .

You could use your original approach with the .tag , but use typedefs.

typedef enum TFTypes {
    TFModalType1,
    TFModalType2,
    TFModalType3,
    TFModalType4,
    TFModalType5,
    ...
} TFType;

I ended up doing largely what I think @Till was trying to suggest. I added an NSMutableArray *tieArray and an int tieCounter as @properties to my view controller. My code for building the UITextFields from the first code block in my OP is now:

for (NSString *key in [theDict allKeys])
{
    UITextField *txt = [[UITextField alloc] initWithFrame:...];
    txt.text = [[(MyBigObject *)[theDict objectForKey:key] box1] name];
    [self.view addSubview:txt];

    txt.tag = self.tieCounter;
    self.tieCounter ++;
    [self.tieArray addObject:[[(MyBigObject *)[theDict objectForKey:key] box1] name]];
}

Then in my textFieldDidEndEditing

- (void) textFieldDidEndEditing:(UITextField *)textField
{
    if ([tieArray objectAtIndex:textField.tag] isKindOfClass:[NSMutableString class]])
    {
        [(NSMutableString *)[tieArray objectAtIndex:textField.tag] setString:textField.text];
    }
    else if (//...More conditions to set other variable types with the syntax as needed)
}

Note that for this to work, all the properties of MySmallObject1 and MySmallObject2 need to be covered by a isKindOfClass: check, and the actual syntax will vary a little depending on what class that property is.

I haven't been able to test this yet (and my app probably won't be in a testable state for quite some time), but it makes sense to me, and it's not throwing any errors or warnings. If I have problems with it when I actually run it I'll update here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!