ios - 当用户在 iOS 的 UITextField 中输入值时,可以不断更新 UILabel 文本

标签 ios objective-c swift uitextfield uilabel

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

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

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

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

这是我的代码

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

最佳答案

您可以为值更改事件注册您的 textField:

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

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

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

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

关于ios - 当用户在 iOS 的 UITextField 中输入值时,可以不断更新 UILabel 文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30977854/

相关文章:

ios - 如何逐行读取 uitextview 文本 iOS?

objective-c - 为什么要初始化父类

ios - 在 UITableViewCell 的背景图像上添加渐变

ios - 将 Podfile 中的 pod 链接到特定目标

objective-c - 使用 NSWorkspace launchApplicationAtURL 启动应用程序后获取退出状态

ios - 如何使用 Swift 动态访问数组中的项目

ios - UiTabController 应用程序设置

ios - 添加到 UITextField 的 CALayer 不会出现在 xib View 上

ios - 带日文字符的 NSString

ios - 在Objective-C中创建后台循环例程的更好方法是什么?