Using a custom font in a UITextField causes it to shift slightly when accessed — is there a fix?

前端 未结 10 1993
后悔当初
后悔当初 2020-12-13 14:32

I have a custom font in a UITextField, and I\'ve noticed that when it\'s accessed (when the keyboard appears), the text shifts down by a very small amount -- maybe

10条回答
  •  暖寄归人
    2020-12-13 14:46

    Swift 3

    Do not forget the accessory views of the UITextField. You'll need to account for super of the *rect(forBounds: ...) functions if you want a working implementation. And be also sure to only displace the rects for the buggy iOS 10 and not for 9 or 8! The following code should do the trick:

    public class CustomTextField: UITextField {
        public override func textRect(forBounds bounds: CGRect) -> CGRect {
            let superValue = super.textRect(forBounds: bounds)
    
            if #available(iOS 10, *) {
                return superValue.insetBy(dx: 0, dy: 0)
            }
            return superValue
        }
    
        public override func editingRect(forBounds bounds: CGRect) -> CGRect {
            let superValue = super.editingRect(forBounds: bounds)
    
            if #available(iOS 10, *) {
                return superValue.insetBy(dx: 0, dy: -0.5)
            }
            return superValue
        }
    
        public override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
            let superValue = super.placeholderRect(forBounds: bounds)
    
            if #available(iOS 10, *) {
                if isEditing {
                    return superValue.insetBy(dx: 0, dy: 0.5)
                }
                return superValue.insetBy(dx: 0, dy: 0.0)
            }
            return superValue
        }
    }
    

    EDIT

    I slightly edited my code from above to the following and it works better for me. I testet it on iPhone 6, 6s, 7, 7s as well as the 'plus' devices with iOS 9.3 and 10.3.

    public class CustomTextField: UITextField {
    
        public override func textRect(forBounds bounds: CGRect) -> CGRect {
            let superValue = super.textRect(forBounds: bounds)
    
            if #available(iOS 10, *) {
                return superValue.insetBy(dx: 0, dy: -0.3)
            }
            return superValue.insetBy(dx: 0, dy: -0.2)
        }
    
        public override func editingRect(forBounds bounds: CGRect) -> CGRect {
            return self.textRect(forBounds: bounds)
        }
    }
    

    I think it also depends on the font you use. I use UIFont.systemFont(ofSize: 17.0, weight: UIFontWeightLight)

提交回复
热议问题