如何设置UITextField的字母间距 [英] How to set letter spacing of UITextField

查看:215
本文介绍了如何设置UITextField的字母间距的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,用户必须键入一个四位数的密码。所有数字必须彼此相距一定距离。

I have an app in which the user has to type a four digit pin code. All digits have to be at a set distance from each other.

如果 PinTextField 是 UIView 的子类?我知道在 ViewController 中你可以使用 UITextFieldTextDidChangeNotification 并为每次更改设置属性文本。通知似乎不适用于 UIView

Is there a way to do this if the PinTextField is a subclass of UIView? I know in a ViewController you could use UITextFieldTextDidChangeNotification and set the attributed text for each change. Notifications don't seem to work in a UIView though.

此外,我想知道是否没有如果你想设置一个 UITextField 文本的字母间距,那么比为每个更新制作一个属性字符串更简单?

Also I was wondering if there isn't a simpler way than making an attributed string for every update if you want to set the letter spacing of a UITextField text ?

正确间距:

错误的间距:

推荐答案

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

This is what eventually worked to set the kern for every change

    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

The problem however remains because different numbers have different widths, I will just resort back to making a UITextField for every digit.

这篇关于如何设置UITextField的字母间距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆