设置UITextField的最大字符长度如何设置UITextField在iPhoneSDK上,当我加载一个UIView?
3 回答
繁星coding
TA贡献1797条经验 获得超4个赞
SWIFT 4
import UIKitprivate var kAssociationKeyMaxLength: Int = 0extension UITextField {
@IBInspectable var maxLength: Int {
get {
if let length = objc_getAssociatedObject(self, &kAssociationKeyMaxLength) as? Int {
return length } else {
return Int.max }
}
set {
objc_setAssociatedObject(self, &kAssociationKeyMaxLength, newValue, .OBJC_ASSOCIATION_RETAIN)
addTarget(self, action: #selector(checkMaxLength), for: .editingChanged)
}
}
@objc func checkMaxLength(textField: UITextField) {
guard let prospectiveText = self.text,
prospectiveText.count > maxLength else {
return
}
let selection = selectedTextRange
let indexEndOfText = prospectiveText.index(prospectiveText.startIndex, offsetBy: maxLength)
let substring = prospectiveText[..<indexEndOfText]
text = String(substring)
selectedTextRange = selection }}- 3 回答
- 0 关注
- 721 浏览
添加回答
举报
0/150
提交
取消
