【问题标题】:It is possible to continuously update the UILabel text as user enter value in UITextField in iOS当用户在 iOS 的 UITextField 中输入值时,可以不断更新 UILabel 文本
【发布时间】:2015-09-07 18:44:23
【问题描述】:

在我的应用程序中,我有一个 UILabelUITextField。最初UILabel 文本为零。
只要用户在UITextField 中输入一些文本,我的UILabel 文本也会更新。

假设当用户在UITextField我的UILabel输入A时立即显示A,在UITextField我的UILabel显示B等等。

为了实现这种行为,我使用了UITextFieldDelegateshouldChangeCharactersInRange 函数。但它总是在一个字符后面。说UITextField text = qwerty 我的UIlabel text show qwert

请帮助我,以便我可以在用户在UITextField 中输入值时不断更新UILabel 文本

这是我的代码

 func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    mylabel.text = textfield.text
   return true
}

【问题讨论】:

  • 请出示您在shouldChangeCharactersInRange中的代码

标签: ios objective-c swift uitextfield uilabel


【解决方案1】:

您可以为值更改事件注册您的文本字段:

[textField addTarget: self action:@selector(textFieldDidChange) forControlEvents:UIControlEventEditingChanged];

并在textFieldDidChange 函数中更新您的标签:

- (void)textFieldDidChange
{
    label.text = textField.text;
}

更需要函数shouldChangeCharactersInRange 来决定是否允许即将发生的更改

【讨论】:

    【解决方案2】:

    您可以使用以下代码更改文本:

    -(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    { 
       myLabel.text = [textField.text stringByReplacingCharactersInRange:range withString:string]
       return YES;
    }
    

    【讨论】:

    • 不,正如 OP 报告的那样,这将落后 1 个字符。对UIControlEventEditingChanged 事件设置一个动作是正确的答案。
    【解决方案3】:

    In Swift

    注册您的编辑事件

    textfield.addTarget(self, action:"changeLabel", forControlEvents:UIControlEvents.EditingChanged)
    
    
    func changeLabel(){
        myLabel.text=textfield.text
    }
    

    【讨论】:

      【解决方案4】:

      您可以使用易于理解的代码:

       - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
      {
         NSString *str = [NSString stringWithFormat:@"%@%@",yourtextfield.text,string];
         NSLog(@"%@",str);
         return YES;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-20
        相关资源
        最近更新 更多