用户在TextField中键入时更新标签

时间:2013-01-30 23:45:07

标签: iphone xcode xcode4.5

当用户输入标签时,我正在尝试用文本字段填充标签:

·H

@interface MainView : UIViewController <UITextFieldDelegate>

还有.m:

-(void)textViewDidChange:(UITextView *)textView
    {
        label.text = textField.text;
    }
- (void)viewDidLoad
    {
        [super viewDidLoad];
        [textField addTarget:self action:@selector(textViewDidChange:) forControlEvents:UIControlEventEditingChanged];
    }

我已将label与标签textField与故事板中的文字字段相关联。

但是加载ViewController时应用程序崩溃了:

* 由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:' - [UILabel addTarget:action:forControlEvents:]:无法识别的选择器发送到实例0x7584ff0'

这里有什么帮助吗? :)

2 个答案:

答案 0 :(得分:3)

您已经在实施UITextFieldDelegate,因此您可以覆盖shouldChangeCharactersInRange,例如:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
     // make sure it is the correct UITextField
     if ([textField isEqual:self.textField]) {
          // update UILabel
          self.label.text = [textField.text stringByReplacingCharactersInRange:range withString:string];
     }
     return YES;
}

答案 1 :(得分:0)

我正在寻找一段时间来做这件事,这很简单:

你在@interface下的.h中的

制作一个计时器

 NSTimer *UpdateLabel;

然后在你的.m做

-(void)UpdateLabel{
Label.text = Textfield.text;
Label.teaxtColor = [UIColor whiteColor];
UIFont *labelfont=[UIFont fontWithName:@"your Font" size:19];
[Label setFont:labelfont];
}

然后在你的viewdidload中执行

UpdateLabel = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(UpdateLabel) userInfo:nil repeats:YES];
相关问题