使用 IBInspectable 在 UITextField 中创建最大字符长度
Create max character length in UITextField using IBInspectable
我想使用 IBInspectable
为我的文本字段创建一个最大长度,我在一个问题 上看到了对此的回答,但我收到一条错误消息 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)
的错误消息,错误消息显示 Expression type '()' is ambiguous without more context
、
我该如何解决?
在Swift 5、String的prefix
方法returns一个String.SubSequence
类型的值
func prefix(_ maxLength: Int) -> Substring
您需要将其转换为 String
类型。
一种方法可能是:
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)
或者如果您更喜欢单行解决方案:
textField.text = String(textField.text!.prefix(maxLength))
我想使用 IBInspectable
为我的文本字段创建一个最大长度,我在一个问题 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)
的错误消息,错误消息显示 Expression type '()' is ambiguous without more context
、
我该如何解决?
在Swift 5、String的prefix
方法returns一个String.SubSequence
func prefix(_ maxLength: Int) -> Substring
您需要将其转换为 String
类型。
一种方法可能是:
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)
或者如果您更喜欢单行解决方案:
textField.text = String(textField.text!.prefix(maxLength))