6

How to set left image icon in UITextView?

with padding because of which cannot overlap image and text on each other.

This is not UItextField,use "UITextView" instead of "UItextField" UItextField it gives inbuilt leftview and rightview which are absent in "UITextView"

class CustomTextView:UITextView{

    /// A UIImage value that set LeftImage to the UITextView
    @IBInspectable open var leftImage:UIImage? {
         didSet {
            if (leftImage != nil) {
               self.leftImage(leftImage!)
            }
        }
    }

fileprivate func leftImage(_ image: UIImage) {
    let icn : UIImage = image
    let imageView = UIImageView(image: icn)
    imageView.frame = CGRect(x: 0, y: 2.0, width: icn.size.width + 20, height: icn.size.height)
    imageView.contentMode = UIViewContentMode.center

}

I hope you understand what I should need.

V D Purohit
  • 1,179
  • 1
  • 10
  • 23

1 Answers1

18

This is the code snippet to make custom UITextView:

//MARK:- CustomTextView
class CustomTextView:UITextView{

    /// A UIImage value that set LeftImage to the UITextView
    @IBInspectable open var leftImage:UIImage? {
        didSet {
            if (leftImage != nil) {
                self.applyLeftImage(leftImage!)
            }
        }
    }


fileprivate func applyLeftImage(_ image: UIImage) {
        let icn : UIImage = image
        let imageView = UIImageView(image: icn)
        imageView.frame = CGRect(x: 0, y: 2.0, width: icn.size.width + 20, height: icn.size.height)
        imageView.contentMode = UIViewContentMode.center
        //Where self = UItextView
        self.addSubview(imageView)
        self.textContainerInset = UIEdgeInsets(top: 2.0, left: icn.size.width + 10.0 , bottom: 2.0, right: 2.0)
    }
}

After write this code select UITextView in Storyboard and give the name of class "CustomTextView" Now go to attribute inspector set your image as left image.

Thank you,

V D Purohit
  • 1,179
  • 1
  • 10
  • 23
  • the functionName leftImage is very weird... a function usually starts with a verb. also the name is the same as the property.. but a getter property -- name it sth like applyLeftImage !? – Daij-Djan Dec 08 '17 at 05:12
  • to align it to left: `imageView.frame = CGRect(x: imageView.frame.width - icon_width - 5, y: 2.0, width: icon_width + 5, height: icon_height)` – Ali Jun 23 '18 at 23:58
  • Doesn't it add the imageView multiple times? – Mikael Nov 09 '18 at 00:47