我想在用户快速输入 UITextField 时计算字符数。
字段和标签的图像:
我已经放置了 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/