【问题标题】:Update label while user is typing in a TextField用户在 TextField 中输入时更新标签
【发布时间】:2014-02-12 09:31:43
【问题描述】:

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

.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'

这里有什么帮助吗? :)

【问题讨论】:

  • 看来您将textField 实例变量链接到UILabel。由于这就是错误消息所说的内容,我必须假设这是发生的事情,除非您在代码中的某个地方更改了 textField 属性指向的内容。

标签: iphone xcode xcode4.5


【解决方案1】:

您已经在实现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;
}

【讨论】:

    【解决方案2】:

    我一直在寻找如何做到这一点,这很简单:

    在你下面的.h @interface 做一个计时器

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

    【讨论】:

      猜你喜欢
      • 2013-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-16
      • 2019-08-27
      • 1970-01-01
      • 2022-11-15
      • 1970-01-01
      相关资源
      最近更新 更多