问题描述
当用户使用swift输入 UITextField 时,我想计算该字符。
I would like to count the character when user keep typing in UITextField with swift.
字段和标签的图像:
我已经放置了UITextField和UILabel,只是没有找到有关Stack溢出的任何信息,如果你可以在 UITextView中做一个我也很感激。
I have already placed UITextField and UILabel, just haven't found any information on Stack overflow, also if you can do one in UITextView I also appreciate it.
推荐答案
要使用下面的函数,您需要实现要计算的文本字段的UITextFieldDelegate协议,每次UITextField更改时都会调用此函数价值:
To use the function below you need to implement the UITextFieldDelegate protocol of the text field you want to count, this function gets called everytime the UITextField change value:
您的班级声明应如下所示
Your class declaration should look something like this
class ViewController: UIViewController, UITextFieldDelegate
你应该有一个 @IBOutlet
与此类似
@IBOutlet var txtValue:UITextField
在viewDidLoad中,您将委托方法设置为self
In viewDidLoad you set the delegate method to 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
//change the value of the label
mylabel.text = String(newLength)
//you can save this value to a global var
//myCounter = newLength
//return true to allow the change, if you want to limit the number of characters in the text field use something like
return newLength <= 25 // To just allow up to 25 characters
return true
}
记住这个函数被调用到所有UITextField所以如果你有很多UITextField你需要添加一个逻辑来知道一个人正在调用这个函数,只需添加一个不同的标签每个UITextField并使用switch语句查找UITextField调用函数
Remember this function is called to all UITextField so if you have many UITextField you will need to add a logic to know witch one is calling this function, just add a different tag to each UITextField and use a switch statement to find with UITextField call the function
这篇关于如何在键入(Swift)时进行实时UITextField计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!