swiftuitextfieldmaxlengthibinspectable

Create max character length in UITextField using IBInspectable


I want to create a max length to my textfield with IBInspectable, I see a answer to this on a question here but I'm getting an error saying Expression type '()' is ambiguous without more context,

My code was

import UIKit

private var __maxLengths = [UITextField: Int]()
extension UITextField {
    @IBInspectable var maxLength: Int {
        get {
            guard let l = __maxLengths[self] else {
               return 150 // (global default-limit. or just, Int.max)
            }
            return l
        }
        set {
            __maxLengths[self] = newValue
            addTarget(self, action: #selector(fix), for: .editingChanged)
        }
    }
    @objc func fix(textField: UITextField) {
        let t = textField.text
        textField.text = t?.prefix(maxLength)
    }
}

and I'm getting an error pointing at textField.text = t?.prefix(maxLength) with an error message saying Expression type '()' is ambiguous without more context,

How can I resolve it?


Solution

  • In Swift 5, String's prefix method returns a value of type String.SubSequence

    func prefix(_ maxLength: Int) -> Substring
    

    You'll need to convert this to a String type.

    One way to do this might be:

    let s = textField.text!.prefix(maxLength) // though UITextField.text is defined as an optional String, can be safely force-unwrapped as the default value is an empty string even when set to nil
    textField.text = String(s)
    

    or if you prefer a single-line solution:

    textField.text = String(textField.text!.prefix(maxLength))