美文网首页
完美解决UITextField输入时文字往下偏移的问题

完美解决UITextField输入时文字往下偏移的问题

作者: wCodeQ | 来源:发表于2017-09-18 12:11 被阅读0次

    在网上看了好多方法,但是实践后都不可以完美解决问题。
    这里解决的需要整合一些方法进行完美解决问题。

    需要新建一个UITextField的子类,重写以下方法:

    override func textRect(forBounds bounds: CGRect) -> CGRect {
            let originalBounds = super.textRect(forBounds: bounds)
            return originalBounds.insetBy(dx: 0, dy: 3)
        }
    
    override func editingRect(forBounds bounds: CGRect) -> CGRect {
            let originalBounds = super.editingRect(forBounds: bounds)
            return originalBounds.insetBy(dx: 0, dy: 3)
        }
    

    这两个方法可以解决当输入超出范围时文字下移问题。

    override func layoutSubviews() {
            super.layoutSubviews()
            for view in self.subviews {
                if let scrollview = view as? UIScrollView {
                    var offset = scrollview.contentOffset
                    if offset.y != 0 {
                        offset.y = 0
                        scrollview.contentOffset = offset
                    }
                    break
                }
            }
        }
    

    重写layoutSubviews将scrollview的contentOffset有偏移的设置为0,可以解决当删除时下移问题。

    重写这几个方法就可以完美解决下移问题。

    参考内容

    相关文章

      网友评论

          本文标题:完美解决UITextField输入时文字往下偏移的问题

          本文链接:https://www.haomeiwen.com/subject/ztzvsxtx.html