user2636197 user2636197 - 1 month ago 32
Swift Question

Swift 3: Show characters remaining in UITextField

I wonder how I can show the characters remaining in a

UITextField
.

Right now I am limiting the characters by:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == TextFieldOne {
guard let text = textField.text else { return true }
let newLength = text.characters.count + string.characters.count - range.length
return newLength <= 55
}
return true
}


What I want to do is to have a
UILabel
that counts down from
55
while you are typing.

I was thinking of adding some sort of logic inside
textFieldDidChange
buy I cant access range from that function.

Answer

You need the UITextFieldDelegate.

Set the delegate in viewDidLoad to the textField Outlet.

And then you use the shouldChangeCharactersInRange function.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var label: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        textField.delegate = self

        // here you set the start value 55 of your label
        label.text = String(55)
    }

}

extension ViewController: UITextFieldDelegate {

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        guard let text = textField.text else { return true }
        let length = text.characters.count + string.characters.count - range.length

        // create an Integer of 55 - the length of your TextField.text to count down
        let count = 55 - length

        // set the .text property of your UILabel to the live created String
        label.text =  String(count)

        // if you want to limit to 55 charakters
        // you need to return true and <= 55

        return length <= 55 // To just allow up to 55 characters
    }

}