如何在 swift 中使用 @IBDesignable 在文本字段的左侧和右侧插入图像?

how to insert image in the left AND right to textfield using @IBDesignable in swift?

我是初学者,我正在尝试制作一个包含两张图片的密码文本字段,一张在左侧(锁定图片),另一张在右侧以像这样显示密码

但我的前辈命令我在文本字段的@IBDesignable class 中进行制作,这样主要代码就不会出现在 UI 中。我在这里

找到了类似的帖子

但似乎代码仅适用于左图或仅适用于右图,我需要它们(锁和眼睛符号)都出现在文本字段中。我试图修改那里的代码,但我无法实现我需要的。真的需要你的帮助,也许你在以前的项目中已经这样做了:)

import UIKit

@IBDesignable


class DesignableTextField: UITextField {

@IBInspectable var rightImage : UIImage? {
    didSet {
      updateRightView()
    }
  }

  @IBInspectable var rightPadding : CGFloat = 0 {
    didSet {
      updateRightView()
    }
  }

    @IBInspectable var leftImage : UIImage? {
        didSet {
            updateView()
        }
    }

    @IBInspectable var leftPadding : CGFloat = 0 {
        didSet {
            updateView()
        }
    }

    @IBInspectable var cornerRadiusOfField : CGFloat = 0 {
        didSet {
            layer.cornerRadius = cornerRadiusOfField
        }
    }



    func updateView() {
        if let image = leftImage {
            leftViewMode = .always

            // assigning image
            let imageView = UIImageView(frame: CGRect(x: leftPadding, y: 0, width: 20, height: 20))
            imageView.image = image

            var width = leftPadding + 20

            if borderStyle == UITextBorderStyle.none || borderStyle == UITextBorderStyle.line {
                width += 5
            }

            let view = UIView(frame: CGRect(x: 0, y: 0, width: width, height: 20)) // has 5 point higher in width in imageView
            view.addSubview(imageView)


            leftView = view

        } else {
            // image is nill
            leftViewMode = .never
        }
    }

func updateRightView() {
    if let image = rightImage {
      rightViewMode = .always

      // assigning image
      let imageView = UIImageView(frame: CGRect(x: rightPadding, y: 0, width: 20, height: 20))
      imageView.image = image

      var width = rightPadding - 20

      if borderStyle == UITextBorderStyle.none || borderStyle == UITextBorderStyle.line {
        width -= 5
      }

      let view = UIView(frame: CGRect(x: 0, y: 0, width: width, height: 20)) // has 5 point higher in width in imageView
      view.addSubview(imageView)


      rightView = view

    } else {
      // image is nill
      rightViewMode = .never
    }
  }



}

另一种方法,在情节提要中添加一个按钮并添加约束,如下所示

  1. 按钮后缘 = 文本框后缘
  2. 按钮(垂直)居中 = 文本框(垂直)居中
  3. 给按钮固定高度和宽度

同样你可以在右边做。 按钮前缘 = 文本框前缘

[]_______________[]

检查以下代码:

@IBInspectable var leftSideImage:UIImage = UIImage() {

    didSet {
        leftView = UIImageView.init(image: leftSideImage)
        leftViewMode = .always
    }
}

@IBInspectable var rightSideImage:UIImage = UIImage() {

    didSet {
        rightView = UIImageView.init(image: rightSideImage)
        rightViewMode = .always
    }
}

输出: