0

So I added a UIImageView to the right of my UITextField, but I need to add a little bit of padding to the right side so that it doesn't anchor all the way to the right. I tried adding a custom frame but that didn't work, so I'm not too sure how to go about getting that padding. Any help would be much appreaciated.

See TextField Example Here

let titleField : UITextField = { let titleField = UITextField() titleField.placeholder = "Title" titleField.textAlignment = .center titleField.backgroundColor = .white titleField.addDoneCancelToolbar() var imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 10, height: 10)) let image = UIImage(systemName: "exclamationmark.circle")?.withTintColor(.systemRed, renderingMode: .alwaysOriginal) imageView.image = image titleField.rightView = imageView titleField.rightViewMode = .always // titleField.rightView?.isHidden = true return titleField }() 
1

2 Answers 2

0

Subclass UITextField and override https://developer.apple.com/documentation/uikit/uitextfield/1619638-rightviewrect.

Sign up to request clarification or add additional context in comments.

Comments

0

Just add the extension :

extension UITextField { func rightImage(_ image: UIImage?, imageWidth: CGFloat, padding: CGFloat) { let imageView = UIImageView() imageView.frame = CGRect(x: padding + 2, y: 0, width: imageWidth, height: frame.height) imageView.contentMode = .scaleAspectFit imageView.image = image let containerView = UIView(frame: CGRect(x: 0, y: 0, width: imageWidth + padding , height: frame.height)) containerView.addSubview(imageView) rightView = containerView rightViewMode = .always } } 

To use it :

if let image = UIImage(named: imagename + ".png") { titlefield.rightImage(image, imageWidth: 30, padding: 5) } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.