UILabel控制另一个视图控制器中的UItextfield

时间:2012-08-01 18:25:26

标签: uiviewcontroller uitextfield uilabel

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

1 个答案:

答案 0 :(得分:0)

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

部首:

@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;