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

时间:2017-11-28 14:30:58

标签: ios swift uitextfield

我在文本字段上创建了一个带有背景图像集的自定义清除按钮。 我将它放在右视图上,但它始终以默认边距定位。我想要的是有一个合适的边距,例如,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 = ""
    }
}

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

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
        //})
    }
}

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

1 个答案:

答案 0 :(得分:1)

您应该查看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
  }
}