8

I have set up the left icon in UITextField. When I set text, it is over the left icon. I want to set text after the icon in the UITextField. I have used below code.

    let imageView = UIImageView(image: UIImage(named: strImgname))
    imageView.frame = CGRect(x: 0, y: 0, width: imageView.image!.size.width , height: imageView.image!.size.height)
    let paddingView: UIView = UIView.init(frame: CGRect(x: 0, y: 0, width: 50, height: 30))        
    paddingView.addSubview(imageView)
    txtField.leftViewMode = .always
    txtField.leftView = paddingView
1
  • 1
    Also updated my answer please follow the steps an in the updated answer to get easy and desired functionality.
    – Rizwan
    Commented Aug 17, 2018 at 6:36

4 Answers 4

12

You can use @IBDesignable to make a designable UITextField with these capabilities and even more and use it through out your project.

DesignableTextField with Delegate methods when icon in UITextField is tapped:

import Foundation
import UIKit

protocol DesignableTextFieldDelegate: UITextFieldDelegate {
    func textFieldIconClicked(btn:UIButton)
}

@IBDesignable
class DesignableTextField: UITextField {

    //Delegate when image/icon is tapped.
    private var myDelegate: DesignableTextFieldDelegate? {
        get { return delegate as? DesignableTextFieldDelegate }
    }

    @objc func buttonClicked(btn: UIButton){
        self.myDelegate?.textFieldIconClicked(btn: btn)
    }

    //Padding images on left
    override func leftViewRect(forBounds bounds: CGRect) -> CGRect {
        var textRect = super.leftViewRect(forBounds: bounds)
        textRect.origin.x += padding
        return textRect
    }

    //Padding images on Right
    override func rightViewRect(forBounds bounds: CGRect) -> CGRect {
        var textRect = super.rightViewRect(forBounds: bounds)
        textRect.origin.x -= padding
        return textRect
    }

    @IBInspectable var padding: CGFloat = 0
    @IBInspectable var leadingImage: UIImage? { didSet { updateView() }}
    @IBInspectable var color: UIColor = UIColor.lightGray { didSet { updateView() }}
    @IBInspectable var imageColor: UIColor = UIColor.init(hex: "3EB2FF") { didSet { updateView() }}
    @IBInspectable var rtl: Bool = false { didSet { updateView() }}

    func updateView() {
        rightViewMode = UITextFieldViewMode.never
        rightView = nil
        leftViewMode = UITextFieldViewMode.never
        leftView = nil

        if let image = leadingImage {
            let button = UIButton(type: .custom)
            button.frame = CGRect(x: 0, y: 0, width: 20, height: 20)

            let tintedImage = image.withRenderingMode(.alwaysTemplate)
            button.setImage(tintedImage, for: .normal)
            button.tintColor = imageColor

            button.setTitleColor(UIColor.clear, for: .normal)
            button.addTarget(self, action: #selector(buttonClicked(btn:)), for: UIControlEvents.touchDown)
            button.isUserInteractionEnabled = true

            if rtl {
                rightViewMode = UITextFieldViewMode.always
                rightView = button
            } else {
                leftViewMode = UITextFieldViewMode.always
                leftView = button
            }
        }

        // Placeholder text color
        attributedPlaceholder = NSAttributedString(string: placeholder != nil ?  placeholder! : "", attributes:[NSAttributedStringKey.foregroundColor: color])
    }
}

Now its Designable in the Storyboard as follows:

enter image description here NOTE: Rtl when set to Off icon will move to left of UITextField

Conforming the Delegate in desired ViewController.

class MyViewController: UIViewController, DesignableTextFieldDelegate {
    @IBOutlet weak var txtFieldSomeSearch: DesignableTextField!
    txtFieldSomeSearch.delegate = self // can be done in storyboard as well
    ... // other codes
    func textFieldIconClicked(btn: UIButton) {
        print("MyViewController : textFieldIconClicked")
    }
    ... // other codes
}

Finally Output :

enter image description here

3
  • 5
    @EnamulHaque You should mark the answer accepted if the answer has solved the problem for you. It is the least you can do considering that people from the community take time out of their day to help a stranger with his problems. Also it helps other people having the same problem identify which is the best solution. Commented Aug 19, 2018 at 14:21
  • Thanks very much! Note that if the device language is set to an RTL language, the meaning of leftView and rightView is switched. They actually behave properly as "leadingView" and "trailingView". So the "rtl" property here might actually confuse things - if you set it to true and you are on a device set to an RTL language, you actually will end up with the opposite of the desired result. Commented Apr 29, 2021 at 22:51
  • @Rizwan, how do you ensure the text doesn't overlap the button when button is right aligned?
    – Ace Green
    Commented May 23, 2023 at 13:56
8

Using the extension in Swift4, We can easily put the image on the right or on the left with padding to TextField.

extension UITextField {

    //MARK:- Set Image on the right of text fields

  func setupRightImage(imageName:String){
    let imageView = UIImageView(frame: CGRect(x: 10, y: 10, width: 20, height: 20))
    imageView.image = UIImage(named: imageName)
    let imageContainerView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 55, height: 40))
    imageContainerView.addSubview(imageView)
    rightView = imageContainerView
    rightViewMode = .always
    self.tintColor = .lightGray
}

 //MARK:- Set Image on left of text fields

    func setupLeftImage(imageName:String){
       let imageView = UIImageView(frame: CGRect(x: 10, y: 10, width: 20, height: 20))
       imageView.image = UIImage(named: imageName)
       let imageContainerView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 55, height: 40))
       imageContainerView.addSubview(imageView)
       leftView = imageContainerView
       leftViewMode = .always
       self.tintColor = .lightGray
     }

  }

Use code as for right image setup:-

self.password_text_field.setupRightImage(imageName: "unlock")

Output :)

enter image description here

3
please use the below code

//Left side icon
textField.leftViewMode = UITextFieldViewMode.Always
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
let image = UIImage(named: imageName)
imageView.image = image
textField.leftView = imageView


//Right side icon
textField.rightViewMode = UITextFieldViewMode.Always
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
let image = UIImage(named: imageName)
imageView.image = image
textField.rightView = imageView
1
  • Some writings would be appreciated. Commented Aug 17, 2018 at 6:17
2

Extension to UITextField in Swift 5. This allows you to check if the image is a system image, otherwise, you use a custom image. You can also set which side of the text field you want the image on using the TextFieldImageSide enumeration.

enum TextFieldImageSide {
    case left
    case right
}

extension UITextField {
    func setUpImage(imageName: String, on side: TextFieldImageSide) {
        let imageView = UIImageView(frame: CGRect(x: 10, y: 5, width: 30, height: 30))
        if let imageWithSystemName = UIImage(systemName: imageName) {
            imageView.image = imageWithSystemName
        } else {
            imageView.image = UIImage(named: imageName)
        }
        
        let imageContainerView = UIView(frame: CGRect(x: 0, y: 0, width: 45, height: 40))
        imageContainerView.addSubview(imageView)
        
        switch side {
        case .left:
            leftView = imageContainerView
            leftViewMode = .always
        case .right:
            rightView = imageContainerView
            rightViewMode = .always
        }
    }
}

Usage:

searchBar.setUpImage(imageName: "mappin.and.ellipse", on: .left)

Produces the following: enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.