iOS 中自定义清除按钮的右边距

Right margin of custom clear button in iOS

我在带有背景图像集的文本字段上创建了一个自定义清除按钮。 我将它定位在正确的视图上,但它始终以默认边距定位。我想要的是右边距,比如8.

extension UITextField {

    func clearButtonWithImage(_ image: UIImage) {
        let clearButton = UIButton()
        clearButton.setBackgroundImage(image, for: .normal)
        clearButton.alpha = 0.25
        clearButton.frame = CGRect(x: 0, y: 0, width: 20, height: 20)

        clearButton.contentMode = .scaleAspectFit
        clearButton.addTarget(self, action: #selector(self.clear(sender:)), for: .touchUpInside)
        self.rightViewMode = .always
        self.clearButtonMode = .never
        self.rightView = clearButton
    }

    @objc func clear(sender: AnyObject) {
        self.text = ""
    }
}

我使用自定义文本字段 class 来更改选择时文本字段的样式。 我的自定义文本字段 Class:

class customSearchTextField: customTextField {
    override var isSelected: Bool {
        didSet {
            setSelected(isSelected)
        }
    }

    private func setSelected(_ selected: Bool) {
        //UIView.animate(withDuration: 0.15, animations: {
        self.transform = selected ? CGAffineTransform(scaleX: 1.05, y: 1.05) : CGAffineTransform.identity
        self.cornerRadius = selected ? 2.0 : 0.0
            if selected {
                self.clearButtonWithImage(UIImage())
            } else {
                self.clearButtonWithImage(#imageLiteral(resourceName: "icClear"))
            }
        self.layer.shadowColor = UIColor .customDark.cgColor
        self.layer.shadowOpacity = selected ? 0.19 : 0.0
        //})
    }
}

尝试定位图像框,但它始终保持不变。

你应该看看 rightViewRect(forBounds:) 方法。在该方法中创建 UITextField 的子类并自定义清除按钮的位置和大小。

例如

class customSearchTextField: customTextField {
  override var isSelected: Bool {
    didSet {
      setSelected(isSelected)
    }
  }

  private func setSelected(_ selected: Bool) {
    //UIView.animate(withDuration: 0.15, animations: {
    self.transform = selected ? CGAffineTransform(scaleX: 1.05, y: 1.05) : CGAffineTransform.identity
    self.cornerRadius = selected ? 2.0 : 0.0
    if selected {
      self.clearButtonWithImage(UIImage())
    } else {
      self.clearButtonWithImage(#imageLiteral(resourceName: "icClear"))
    }
    self.layer.shadowColor = UIColor .customDark.cgColor
    self.layer.shadowOpacity = selected ? 0.19 : 0.0
    //})
  }

  override func rightViewRect(forBounds bounds: CGRect) -> CGRect {
    var rect = super.rightViewRect(forBounds: bounds)
    rect.origin.x -= 30 // Assume your right margin is 30
    return rect
  }
}