首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何设置UITextField的字母间距

如何设置UITextField的字母间距
EN

Stack Overflow用户
提问于 2015-08-07 19:47:53
回答 6查看 20.4K关注 0票数 51

我有一个应用程序,其中用户必须键入一个四位数的pin代码。所有数字必须彼此之间有一定的距离。

如果PinTextFieldUIView的子类,有什么方法可以做到这一点吗?我知道在ViewController中,您可以使用UITextFieldTextDidChangeNotification并为每个更改设置属性文本。不过,在UIView中通知似乎不起作用。

另外,我想知道,如果您想设置UITextField文本的字母间距,有没有比每次更新都创建一个属性字符串更简单的方法?

更正间距:

错误的间距:

EN

回答 6

Stack Overflow用户

发布于 2015-08-10 17:00:25

这就是最终为每个更改设置kern的原因

代码语言:javascript
复制
    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

票数 11
EN

Stack Overflow用户

发布于 2017-09-24 22:35:22

使用UITextFielddefaultTextAttributes属性。它将为您处理到NSAttributedString的转换,并应用您设置的属性。例如:

代码语言:javascript
复制
    NSMutableDictionary *attrs = [self.textField.defaultTextAttributes mutableCopy];
[attrs addEntriesFromDictionary:@{
    NSKernAttributeName: @18,
    NSUnderlineColorAttributeName: [UIColor grayColor],
    NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle | NSUnderlinePatternDash)
}];
self.textField.defaultTextAttributes = attrs;
票数 4
EN

Stack Overflow用户

发布于 2015-08-07 20:02:29

不太确定是否有其他解决方案,而不是使用属性字符串。

但是对于通知部分,您可以将textFields委托设置为UIView,并在视图中定义下面的方法。

代码语言:javascript
复制
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string; 

每次在文本字段中输入的文本发生更改时,都会调用上述方法。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31877002

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档