我有一个应用程序,用户必须键入一个四位数的引脚代码.所有数字必须距离彼此设定的距离.
如果PinTextField是UIView的子类,是否有办法?我知道在ViewController中,您可以使用UITextFieldTextDidChangeNotification,并为每次更改设置归因文本.通知在UIView中似乎不起作用.
另外我想知道如果你想设置一个UITextField文本的字母间距,是不是比每个更新的属性字符串更简单的方法?
正确间距:
间距错误
解决方法
这是最终为每一个变化而设定的核心
textField.addTarget(self,action: "textFieldDidChange",forControlEvents: .EditingChanged)
func textFieldDidChange () {
let attributedString = NSMutableAttributedString(string: textField.text)
attributedString.addAttribute(NSKernAttributeName,value: 5,range: NSMakeRange(0,count(textField.text)))
attributedString.addAttribute(NSFontAttributeName,value: font,count(textField.text)))
attributedString.addAttribute(NSForegroundColorAttributeName,value: UIColor.blackColor(),count(textField.text)))
textField.attributedText = attributedString
}
func textField(textField: UITextField,shouldChangeCharactersInRange range: NSRange,replacementString string: String) -> Bool {
if count(textField.text) < 4 {
return true
// Else if 4 and delete is allowed
}else if count(string) == 0 {
return true
// Else limit reached
}else{
return false
}
}
然而,问题依然存在,因为不同的数字有不同的宽度,我只是回到为每个数字制作一个UITextField.