Create max character length in UITextField using IBInspectable [duplicate]

冷暖自知 提交于 2020-06-17 09:45:14

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/62165247/create-max-character-length-in-uitextfield-using-ibinspectable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!