Create max character length in UITextField using IBInspectable [duplicate]
Asked Answered
S

1

1

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?

Ship answered 3/6, 2020 at 4:30 Comment(3)
Can you remove @objc annotation in front of func fix? I think it causes this error.Gnatcatcher
@Sung-JongWillKim @objc is requiredPhytogeography
oh, selector is linked.Gnatcatcher
R
2

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))
Rule answered 3/6, 2020 at 5:8 Comment(4)
UITextField text property default value is an empty string. Keeping t optional is pointlessPhytogeography
UITextField.text is defined as an optional String. I was just keeping inline with OP's original code. open var text: String? // default is nilRule
UITextField text property value will NEVER be nilPhytogeography
Thanks for keeping me honest. The "Jump to definition" action reveals what appears to be an outdated comment in the UITextField code. I'll edit the answerRule

© 2022 - 2024 — McMap. All rights reserved.