1 设置代理
继承UITextFieldDelegate
tfTime.delegate =self;
tfCMD.delegate =self;
2 实现代理
func textField(textField:UITextField,shouldChangeCharactersInRange range:NSRange,replacementString string: String) -> Bool {
iftfTime == textField {
//限制只能输入数字,不能输入特殊字符
let length = string.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)
for loopIndexin0..<length {
let char = (stringas NSString).characterAtIndex(loopIndex)
if char <48 {return false }
if char >57 {return false }
}
//限制长度
let proposeLength = (textField.text?.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))! - range.length + string.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)
if proposeLength >4 { return false }
}
iftfCMD == textField {
let length = string.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)
for loopIndexin0..<length {
let char = (stringas NSString).characterAtIndex(loopIndex)
//只能输入 a~z A~Z
if char <65 {return false }
if char >=91 && char <=112 {returnfalse }
if char >=123 {returnfalse }
}
}
return true
}
原文链接:https://www.f2er.com/swift/321574.html