UITextField限制长度
1、字符串截取
extension String {
func substring(start: Int, _ count: Int) -> String {
let begin = index(startIndex, offsetBy: max(0, start))
let end = index(startIndex, offsetBy: min(count, start + count))
return String(self[begin..<end])
}
}
2、UITextField限制长度
static func clipTextFieldTextLength(textField: UITextField, limitNum: Int) -> String? {
var finalText = textField.text
if let text = textField.text, limitNum > 0 && text.count > limitNum {
if let language = UITextInputMode.activeInputModes.first?.primaryLanguage, language == "zh-Hans", let range = textField.markedTextRange {
let start = range.start
let end = range.end
let selLength = textField.offset(from: start, to: end)
let contentLength = text.count - selLength
if (contentLength > limitNum) {
finalText = text.substring(start: 0, limitNum)
}
} else {
finalText = text.substring(start: 0, limitNum)
}
}
return finalText
}