美文网首页
Swift限制输入框输入

Swift限制输入框输入

作者: 做个有趣的程序员 | 来源:发表于2018-06-27 17:32 被阅读0次

项目里涉及到输入框的输入会有各种限制,最常见的就是限制输入长度,限制特殊字符的输入。
限制长度:

extension String {
    public func substring(from index: Int) -> String {
        if self.count > index {
            let endIndex = self.index(self.startIndex, offsetBy: index)
            let subString = self[self.startIndex..<endIndex]
            
            return String(subString)
        } else {
            return self
        }
    }
}

限制特殊字符:

let testString = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    //如果是输入的123abcABC除了数字和字符之外的,禁止输入
    let char = NSCharacterSet.init(charactersIn: testString).inverted
    let inputString = string.components(separatedBy: char).joined(separator: "")
    return string == inputString
}

相关文章

网友评论

      本文标题:Swift限制输入框输入

      本文链接:https://www.haomeiwen.com/subject/tgciyftx.html