1

我正在使用 Xcode 4.3,并且我在一个视图控制器中有一个标签,我想更新另一个视图控制器中文本字段中的文本。我该怎么做?

4

1 回答 1

0

您应该将文本放在模型类中(假设您有一个;如果没有,则需要创建它)。当最终用户编辑文本字段时,您的代码应该更改模型中的字符串;当标签显示时,您应该从模型中读取其文本。在多个类之间共享模型的最简单方法是定义一个单例

标题:

@interface Model : NSObject
@property (NSString*) labelText;
+(Model*)instance;
@end

执行:

@implementation Model
@synthesize labelText;
+(Model*)instance{
    static Model *inst;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        inst = [[Model alloc] init];
    });
    return inst;
}
-(id)init {
    if (self = [super init]) {
        labelText = @"Initial Text";
    }
    return self;
}
@end

使用模型:

// Setting the field in the model, presumably in textFieldDidEndEditing:
// of your UITextField delegate
[Model instance].labelText = textField.text;

// Getting the field from the model, presumably in viewWillAppear
myLabel.text = [Model instance].labelText;
于 2012-08-01T18:30:21.383 回答