How to do a live UITextField count while typing (Swift)?

后端 未结 10 1197
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-05 13:37

I would like to count the character when user keep typing in UITextField with swift.

Image of Field and Label:

相关标签:
10条回答
  • 2020-12-05 14:15

    For multiple 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
     }
    }
    
    0 讨论(0)
  • 2020-12-05 14:16

    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 UITextFields text changes:

    Your class declaration should look something like this

    class ViewController: UIViewController, UITextFieldDelegate
    

    You should have an @IBOutlet similar to this

    @IBOutlet var txtValue: UITextField
    

    Set the UITextField s delegate 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
    
        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 UITextFields so if you have several UITextFields you will need to add a logic to know witch one is calling this function.

    0 讨论(0)
  • 2020-12-05 14:17

    This will only allow your textfield input 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
        }
    }
    }
    

    And Screenshot

    enter image description here

    0 讨论(0)
  • 2020-12-05 14:23

    Here's how you could do it in Swift 3/4.

    First, make sure you've got your textField's delegate set in viewDidLoad.

    yourTextField.delegate = self
    

    Then, implement 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

    0 讨论(0)
  • 2020-12-05 14:27

    UITextView count while typing in Swift:

    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
        }
    
    0 讨论(0)
  • 2020-12-05 14:28

    Swift 5.1

    Add viewController delegate

    final class CreditCardViewController : BaseViewController , UITextFieldDelegate {
    
        @IBOutlet var cvvTextField: UITextField!
    

    Add 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
        }
    
    0 讨论(0)
提交回复
热议问题