使用 IBInspectable 在 UITextField 中创建最大字符长度 [英] Create max character length in UITextField using IBInspectable
问题描述
我想使用 IBInspectable
为我的文本字段创建最大长度,我在问题 here 但我收到一个错误提示 Expression type '()' 在没有更多上下文的情况下不明确
,
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
,
我的代码是
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)
}
}
并且我在 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
,
我该如何解决?
推荐答案
在 Swift 5 中,String 的 prefix
方法返回 String.SubSequence
In Swift 5, String's prefix
method returns a value of type String.SubSequence
func prefix(_ maxLength: Int) -> Substring
您需要将其转换为 String
类型.
You'll need to convert this to a String
type.
一种方法可能是:
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))
这篇关于使用 IBInspectable 在 UITextField 中创建最大字符长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!