UITextView 左侧图像图标 swift

UITextView left image icon swift

如何在 UITextView 中设置左图图标?

带填充,因为它不能使图像和文本相互重叠。

这不是 UItextField,使用 "UITextView" 而不是 "UItextField" UItextField 它提供了 "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

}

希望你明白我需要什么。

这是制作自定义 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)
    }
}

在 Storyboard 中编写此代码 select UITextView 并命名 class "CustomTextView" 现在转到属性检查器将您的图像设置为左图像。

谢谢,