二、实现代码
注意,这段代码会将所有的空格及字符串去掉,如果只去除两端的可以使用上面的代码
- (NSString *)removeSpaceAndNewline:(NSString *)str
{
NSString *temp = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
temp = [temp stringByReplacingOccurrencesOfString:@"\r" withString:@""];
temp = [temp stringByReplacingOccurrencesOfString:@"\n" withString:@""];
return temp;
}
3.控制TextField只能接受显示控制内的字符:
控制输入的字符,只需要遵守UITextFieldDelegate代理,实现代理方法即可,具体操作在代理方法
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
然后在代理方法中实现即可;
<1>引入协议
<2>设置代理
<3>实现协议方法
第一步第二步不做代码演示了。第三步代理:
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if textField.tag == 101 {
let characterSet = NSCharacterSet(charactersInString: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789").invertedSet
let filtered = string.componentsSeparatedByCharactersInSet(characterSet)
let ss = filtered.joinWithSeparator("")
return ss == string
}
return true
}