ios 键入 (Swift) 时如何进行实时 UITextField 计数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30656501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to do a live UITextField count while typing (Swift)?
提问by Farhad
I would like to count the character when user keep typing in UITextFieldwith swift.
当用户继续快速输入UITextField时,我想计算字符。
Image of Field and Label:
字段和标签的图像:
I have already placed UITextField and UILabel, just haven't found any information on Stack overflow, also if you can do one in UITextViewI also appreciate it.
UITextField 和 UILabel 我已经放好了,只是没有找到 Stack overflow 的任何信息,如果你能在UITextView 中做一个我也很感激。
回答by Icaro
To use the function below you need to implement the UITextFieldDelegate protocol
on the text field you want to count. This gets called every time the UITextField
s text changes:
要使用下面的函数,您需要UITextFieldDelegate protocol
在要计数的文本字段上实现。每次UITextField
s 文本更改时都会调用它:
Your class declaration should look something like this
你的类声明应该是这样的
class ViewController: UIViewController, UITextFieldDelegate
You should have an @IBOutlet
similar to this
你应该有一个@IBOutlet
类似的
@IBOutlet var txtValue: UITextField
Set the UITextField
s delegate to self
.
将UITextField
s 委托设置为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
}
Note that this function is called on all UITextField
s so if you have several UITextField
s you will need to add a logic to know witch one is calling this function.
请注意,此函数会在所有UITextField
s上调用,因此如果您有多个UITextField
s,则需要添加一个逻辑来知道某个人正在调用此函数。
回答by Yash Tamakuwala
A very elegant and neat solution exists using UITextFieldDelegate. My solution uses the concept of selectors. In a selector you tell your compiler what function/action to perform when a particular event happens. In this case - typing in textfield. Make sure that you have set the textField delegate in storyboard.
使用 UITextFieldDelegate 存在一个非常优雅和简洁的解决方案。我的解决方案使用了选择器的概念。在选择器中,您告诉编译器在特定事件发生时要执行的功能/操作。在这种情况下 - 在文本字段中输入。确保您已在故事板中设置了 textField 委托。
override func viewDidLoad() {
super.viewDidLoad()
yourTextField.addTarget(self, action: #selector(YourViewController.textFieldDidChange(_:)), forControlEvents: UIControlEvents.EditingChanged)
}
func textFieldDidChange(textField : UITextField){
label.text = yourTextField.text?.characters.count
}
回答by MinnuKaAnae
For multiple UITextView
对于多个 UITextView
class ViewController: UIViewController, UITextViewDelegate {
@IBOutlet weak var ticketSummaryTV: UITextView!
@IBOutlet weak var ticketDescriptionTV: UITextView!
@IBOutlet weak var summaryCountLbl: UILabel!
@IBOutlet weak var descriptionCountLbl: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
ticketSummaryTV.delegate = self
ticketDescriptionTV.delegate = self
self.updateCharacterCount()
}
func updateCharacterCount() {
let summaryCount = self.ticketSummaryTV.text.characters.count
let descriptionCount = self.ticketDescriptionTV.text.characters.count
self.summaryCountLbl.text = "\((0) + summaryCount)/50"
self.descriptionCountLbl.text = "\((0) + descriptionCount)/500"
}
func textViewDidChange(_ textView: UITextView) {
self.updateCharacterCount()
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool{
if(textView == ticketSummaryTV){
return textView.text.characters.count + (text.characters.count - range.length) <= 50
}else if(textView == ticketDescriptionTV){
return textView.text.characters.count + (text.characters.count - range.length) <= 500
}
return false
}
}
回答by Leo
This will only allow your textfield input 14 char
这将只允许您的文本字段输入 14 个字符
class ViewController: UIViewController,UITextFieldDelegate {
@IBOutlet weak var textfield: UITextField!
@IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.label.text = "14"
self.textfield.delegate = self
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let newLength = count(textField.text.utf16) + count(string.utf16) - range.length
if(newLength <= 14){
self.label.text = "\(14 - newLength)"
return true
}else{
return false
}
}
}
And Screenshot
和截图
回答by guest
In Swift
viewDidLoad {
self.yourTextView.delegate = self
self.updateCharacterCount()
}
func updateCharacterCount() {
self.yourLabel.text = "\((65) - self.yourTextView.text.characters.count)"
}
func textViewDidChange(textView: UITextView) {
self.updateCharacterCount()
}
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
self.updateCharacterCount()
return textView.text.characters.count + (text.characters.count - range.length) <= 65
}
回答by ikbal
Swift 5.1
斯威夫特 5.1
Add viewController
delegate
添加viewController
委托
final class CreditCardViewController : BaseViewController , UITextFieldDelegate {
@IBOutlet var cvvTextField: UITextField!
Add viewDidLoad()
添加 viewDidLoad()
cvvTextField.delegate = self
And add delegate function.
并添加委托功能。
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if(textField == cvvTextField){
let characterCountLimit = 3
let startingLength = textField.text?.count ?? 0
let lengthToAdd = string.count
let lengthToReplace = range.length
let newLength = startingLength + lengthToAdd - lengthToReplace
return newLength <= characterCountLimit
}
return true
}
回答by Adrian
Here's how you could do it in Swift 3/4.
以下是您如何在 Swift 3/4 中做到这一点。
First, make sure you've got your textField's delegate set in viewDidLoad
.
首先,请确保您已将 textField 的委托设置为viewDidLoad
.
yourTextField.delegate = self
Then, implement shouldChangeCharactersIn
:
然后,实施shouldChangeCharactersIn
:
extension YourViewController: UITextFieldDelegate {
func textField(_ textFieldToChange: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// limit to 4 characters
let characterCountLimit = 4
// We need to figure out how many characters would be in the string after the change happens
let startingLength = textFieldToChange.text?.characters.count ?? 0
let lengthToAdd = string.characters.count
let lengthToReplace = range.length
let newLength = startingLength + lengthToAdd - lengthToReplace
return newLength <= characterCountLimit
}
}
Additional details here
此处的其他详细信息
回答by mr.byte
Swift 4 for UITextView
change text event UITextViewDelegate
Swift 4 用于UITextView
更改文本事件UITextViewDelegate
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
}