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
    }()
RapsIn4
  • 91
  • 5

2 Answers2

0

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

matt
  • 515,959
  • 87
  • 875
  • 1,141
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)
}
JarWarren
  • 1,343
  • 2
  • 13
  • 18
AJ16
  • 56
  • 4