键入时如何进行实时UITextField计数(Swift)?

时间:2015-06-05 00:36:07

标签: ios swift uitextfield uitextview

我想在用户使用swift输入 UITextField 时计算该字符。

Field and Label图片:

enter image description here

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

11 个答案:

答案 0 :(得分:24)

要使用下面的功能,您需要在要计算的文本字段上实现UITextFieldDelegate protocol。每次UITextField文本更改时都会调用此方法:

你的班级声明应该是这样的

class ViewController: UIViewController, UITextFieldDelegate

你应该有@IBOutlet与此相似

@IBOutlet var txtValue: UITextField

UITextField委托设为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,则需要添加一个逻辑来了解一个人正在调用此函数。

答案 1 :(得分:15)

使用UITextFieldDelegate存在一个非常优雅和整洁的解决方案。我的解决方案使用了选择器的概念。在选择器中,您告诉编译器在特定事件发生时要执行的功能/操作。在这种情况下 - 在文本字段中键入。确保在storyboard中设置了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
}

答案 2 :(得分:7)

多个UITextView

enter image description here

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
 }
}

答案 3 :(得分:5)

这将只允许你的文本字段输入14 char

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
    }
}
}

和截图

enter image description here

答案 4 :(得分:3)

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
}

答案 5 :(得分:0)

以下是你在Swift 3/4中的表现。

首先,确保在viewDidLoad中设置了textField的委托。

yourTextField.delegate = self

然后,实施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
    } 
}

其他详细信息here

答案 6 :(得分:0)

Swift 4 for UITextView更改文字事件UITextViewDelegate

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {

}

答案 7 :(得分:0)

Swift 5.1

添加viewController代表

final class CreditCardViewController : BaseViewController , UITextFieldDelegate {

    @IBOutlet var cvvTextField: UITextField!

添加viewDidLoad()

cvvTextField.delegate = self

并添加委托函数。

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
    }

答案 8 :(得分:0)

在Swift中输入

UITextView的次数:

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {

        let textCount = textView.text?.count ?? 0 + text.count - range.length
        self.textCountLabel.text  = "\(textCount)"
        return true
    }

答案 9 :(得分:0)

Swift 5.3

在带有插座的viewController中添加 UITextFieldDelegate

class ViewController: UIViewController, UITextFieldDelegate{
     @IBOutlet weak var txtGroupName: UITextField!
     @IBOutlet weak var lblWordCount: UILabel!

在您的 viewDidLoad()中添加 textfeild委托,如下所示

override func viewDidLoad() {
   super.viewDidLoad()
   txtGroupName.addTarget(self, action: #selector(self.textFieldDidChange(textField:)), for: UIControl.Event.editingChanged)
  }
    
   @objc func textFieldDidChange(textField : UITextField){
    self.lblWordCount.text = "\(self.txtGroupName.text!.count)/"+"\(65)"
  }

我们还设置了最低文本限制65 。您可以将65替换为所需的

extension viewController:UITextFieldDelegate{
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if !(textField.text?.isEmpty ?? true){
            return textField.text!.count +  (string.count - range.length) <= 65
        }
        return true
    }
}

它的输出如下所示

output

答案 10 :(得分:0)

简单...

像这样将 UITextViewDelegate 添加到您的类标题中...

class ViewController: UIViewController, UITextFieldDelegate { ... }

像这样将 @IBOutlet 添加到 UILabelUITextView...

@IBOutlet weak var characterCountLabel: UILabel!
@IBOutlet var characterTextField: UITextView!

然后将以下委托添加到 viewDidLoad() 函数中...

override func viewDidLoad() {
    super.viewDidLoad()
    self.characterTextField.delegate = self // required for character counter
}

最后,只需为 func 委托方法创建一个 textViewDidChange...

func textViewDidChange(_ textView: UITextView) {
    self.characterCountLabel.text = String("\(textView.text.count)")
}

我亲自检查并验证了这种为您的 UITextView 添加文本计数器并将其输出到 UILabel 的简单方法并且它有效!