V D Purohit
V D Purohit

Reputation: 1189

UITextView left image icon swift

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.

Upvotes: 6

Views: 4185

Answers (1)

V D Purohit
V D Purohit

Reputation: 1189

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,

Upvotes: 18

Related Questions