Swift: UITextfield 只能输入数字或字母,限制长度

前端之家收集整理的这篇文章主要介绍了Swift: UITextfield 只能输入数字或字母,限制长度前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

猜你在找的Swift相关文章