ios - 如何在打字时进行实时 UITextField 计数(Swift)?

标签 ios swift uitextfield uitextview

我想在用户快速输入 UITextField 时计算字符数。

字段和标签的图像:

enter image description here

我已经放置了 UITextField 和 UILabel,只是没有找到任何关于 Stack overflow 的信息,如果你能在 UITextView 中做一个,我也很感激。

最佳答案

要使用下面的函数,您需要在要计数的文本字段上实现 UITextFieldDelegate 协议(protocol)。每次 UITextField 的文本更改时都会调用此方法:

你的类声明应该是这样的

class ViewController: UIViewController, UITextFieldDelegate

你应该有一个类似这样的@IBOutlet

@IBOutlet var txtValue: UITextField

UITextField 的委托(delegate)设置为 self

override func viewDidLoad() {
    super.viewDidLoad()
    txtValue.delegate = self                
}

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    let newLength = count(textField.text.utf16) + count(string.utf16) - range.length

    mylabel.text =  String(newLength) // Set value of the label
    // myCounter = newLength // Optional: Save this value
    // return newLength <= 25 // Optional: Set limits on input. 
    return true
}

请注意,此函数会在所有 UITextField 上调用,因此如果您有多个 UITextField,您将需要添加一个逻辑以了解哪个女巫正在调用此函数。

关于ios - 如何在打字时进行实时 UITextField 计数(Swift)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30656501/

相关文章:

swift - 如何编写 map、filter、reduce 等高阶函数?

swift - 带有自定义对象的 setObjectForKey 方法在 NSUserDefaults swift 中不起作用

ios - tableView heightForRowAtIndexPath 不工作

ios - 如何在文本字段中执行多个自动完成?

ios - TouchID 后应用程序变为事件状态时键盘不可见

ios - 本地化 : Which is a better approach of the following?

objective-c - 将年份组件添加到伊斯兰日历失败

swift - UITextField 打开时被键盘部分隐藏

ios - 控制缩放行为 ARKit

ios - ReactiveCocoa : disposing of a repeating signal