uitextfield左视图中的标签未与文本对齐 [英] Label in uitextfield left view not aligned with the text

查看:154
本文介绍了uitextfield左视图中的标签未与文本对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用左视图制作带有标签的自定义textField,但是标签的文本与textField的文本/占位符不对齐.

I'm making a custom textField with a label in his left view but the text of the label is not aligned with the text/placeholder of the textField.

这是我的简单代码:

 class mytextfield: UITextField {

    override init(frame: CGRect) {
        super.init(frame: frame)

        leftViewMode = .always
        let label = UILabel()

        label.text = "Hello"
        leftView = label
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func leftViewRect(forBounds bounds: CGRect) -> CGRect {
        return CGRect(x: 0, y: 0, width: 40, height: bounds.height)
    }
}

在模拟器上显示结果(我用红色下划线标出了区别)并调试视图层次结构:

Here the result on simulator (I underlined in red to see the difference) and debug view hierarchy:

该如何解决?

推荐答案

这可能是两个视图都使用字体样式或框架绑定大小进行渲染的问题.尝试为左标签视图调整y-positionheight.

This may be issue of rendering with font style or bound size of frame for both views. Try to adjust y-position or height for left label view.

这不是您要查找的确切答案.但这可能会解决您的问题.

This's not an exact answer, that you are looking for. But this may solve your problem.

override func leftViewRect(forBounds bounds: CGRect) -> CGRect {
    return CGRect(x: 0, y: 0, width: 40, height: (bounds.height - 4))
}

override func leftViewRect(forBounds bounds: CGRect) -> CGRect {
    return CGRect(x: 0, y: -2, width: 40, height: bounds.height)
}


我已经尝试过了:

class LeftViewTextfield: UITextField {

    override init(frame: CGRect) {
        super.init(frame: frame)

        leftViewMode = .always
        let label = UILabel()
        label.backgroundColor = UIColor.yellow
        label.text = "Hello"
        label.font = UIFont.systemFont(ofSize: 16)
        leftView = label
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func leftViewRect(forBounds bounds: CGRect) -> CGRect {
        return CGRect(x: 0, y: -0.5, width: 40, height: bounds.height)
    }
}


class TestViewController: UIViewController {

    var textField: LeftViewTextfield?
    override func viewDidLoad() {
        super.viewDidLoad()

        setupTextField()
    }

    func setupTextField() -> Void {
        textField = LeftViewTextfield(frame: CGRect(x: 40, y: 40, width: 100, height: 40))
        textField?.text = "Hello"
        textField?.font = UIFont.systemFont(ofSize: 16)
        textField?.backgroundColor = UIColor.orange
        self.view.addSubview(textField!)
    }

}

结果:

这篇关于uitextfield左视图中的标签未与文本对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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