如何设置UITextField的字母间距

KMV*_*KMV 36 objective-c uitextfield ios swift

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

如果它PinTextField是一个子类,有没有办法做到这一点UIView?我知道ViewController你可以使用UITextFieldTextDidChangeNotification并为每个更改设置属性文本.通知似乎不起作用UIView.

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

正确的间距:

TextField具有正确的间距

间距错误:

TextField的间距错误

iOS*_*Ser 35

没有必要去为belongsText,说实话,是修改间距实现的混乱.当我关闭键盘时,间距消失了,这促使我进一步挖掘.

每个UITextField都有一个名为defaultTextAttributes的属性,根据Apple "返回带有默认值的文本属性字典"..在苹果公司的文件还指出,"该属性指定属性的文本字段的整个文本"

只需在代码中找到合适的位置,通常是在初始化文本字段的位置,然后复制并粘贴以下内容.

在Swift 3.0中回答

textfield.defaultTextAttributes.updateValue(spacing, forKey: NSKernAttributeName)
Run Code Online (Sandbox Code Playgroud)

其中间距是CGFloat类型.例如2.0

这适用于不同的字体.

干杯!!


最新的语法似乎是:

 yourField.defaultTextAttributes.updateValue(36.0, 
     forKey: NSAttributedString.Key.kern)
Run Code Online (Sandbox Code Playgroud)

  • @Fattie感谢您添加最新语法和评论.:) (2认同)

KMV*_*KMV 10

这是最终为每次改变设置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
        }
    }
Run Code Online (Sandbox Code Playgroud)

然而问题仍然存在,因为不同的数字有不同的宽度,我只想回到UITextField每个数字.

  • 正确的解决方案是使用等宽字体。 (3认同)