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