我有一个应用程序,其中用户必须键入一个四位数的pin代码。所有数字必须彼此之间有一定的距离。
如果PinTextField
是UIView
的子类,有什么方法可以做到这一点吗?我知道在ViewController
中,您可以使用UITextFieldTextDidChangeNotification
并为每个更改设置属性文本。不过,在UIView
中通知似乎不起作用。
另外,我想知道,如果您想设置UITextField
文本的字母间距,有没有比每次更新都创建一个属性字符串更简单的方法?
更正间距:
错误的间距:
发布于 2015-08-10 17:00:25
这就是最终为每个更改设置kern的原因
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, range: NSMakeRange(0, count(textField.text)))
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.blackColor(), range: NSMakeRange(0, 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
。
发布于 2017-09-24 22:35:22
使用UITextField
的defaultTextAttributes
属性。它将为您处理到NSAttributedString
的转换,并应用您设置的属性。例如:
NSMutableDictionary *attrs = [self.textField.defaultTextAttributes mutableCopy];
[attrs addEntriesFromDictionary:@{
NSKernAttributeName: @18,
NSUnderlineColorAttributeName: [UIColor grayColor],
NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle | NSUnderlinePatternDash)
}];
self.textField.defaultTextAttributes = attrs;
发布于 2015-08-07 20:02:29
不太确定是否有其他解决方案,而不是使用属性字符串。
但是对于通知部分,您可以将textFields
委托设置为UIView
,并在视图中定义下面的方法。
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
每次在文本字段中输入的文本发生更改时,都会调用上述方法。
https://stackoverflow.com/questions/31877002
复制相似问题