Reputation: 2817
I am using below code for adding left view in textfield:
func setUI()
{
txtUserCode.leftViewMode = .always
let label = UILabel(frame: CGRect(x: 7, y: 0, width: 18, height: txtUserCode.frame.size.height))
label.text = "@"
txtUserCode.leftView?.frame = CGRect(x: 0, y: 0, width: 18, height: txtUserCode.frame.size.height)
txtUserCode.leftView = label
label.backgroundColor = UIColor.green
txtUserCode.leftView?.backgroundColor = UIColor.red
}
But the problem is there is gap between left view and curser you can see in screen shot.
See there is small gap between curser and the left view, you can see between 'premB' and '@'
Any help or suggestion will be helpful.
Upvotes: 0
Views: 52
Reputation: 31647
Update your code to below.
func setUI()
{
txtUserCode.leftViewMode = .always
let label = UILabel(frame: CGRect(x: 7, y: 0, width: 18, height: txtUserCode.frame.size.height))
label.text = "@"
label.sizeToFit()
label.frame = CGRect(x: 7, y: 0, width: label.frame.size.width, height: txtUserCode.frame.size.height)
txtUserCode.leftView?.frame = CGRect(x: 0, y: 0, width: label.frame.size.width, height: txtUserCode.frame.size.height)
txtUserCode.leftView = label
label.backgroundColor = UIColor.green
txtUserCode.leftView?.backgroundColor = UIColor.red
}
To get the exact size, first make sizeToFit for the label & instead of 18, give the width of the label.
Add below line and try again.
txtUserCode.borderStyle = .none
Upvotes: 1