问题
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.
Here my simple code:
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:
How to fix this?
回答1:
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))
}
or
override func leftViewRect(forBounds bounds: CGRect) -> CGRect {
return CGRect(x: 0, y: -2, width: 40, height: bounds.height)
}
I've tried this:
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!)
}
}
Result:
回答2:
You do:
let label = UILabel()
label.text = "Hello"
leftView = label
The issue is that the default baselines, insets layouts, text containers of a UILabel is not the same as the one by default used for a UITextField.
They are not the same between a UITextView and a UILabel too. Just check this related question (they are others on SO too). Author superpose a UITextView and a UILabel and the rendering is different.
Quick way to do so, avoiding repeating the whole internal layout settings of the UITextField and replicate it on the UILabel is to set the leftView as a UITextField. Just make it "non-selectable/non-editable" and it should make a perfect illusion.
来源:https://stackoverflow.com/questions/51078259/label-in-uitextfield-left-view-not-aligned-with-the-text