Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 587
V D Purohit Avatar asked Dec 03 '22 20:12

V D Purohit


1 Answers

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,

like image 99
V D Purohit Avatar answered Dec 21 '22 09:12

V D Purohit