iOS中自定义清除按钮的右边距
我使用背景图像集在文本字段上创建自定义清除按钮。 我将其放置在右视图上,但它始终以默认边距放置。我想要的是有一个右边距,例如,8iOS中自定义清除按钮的右边距,ios,swift,uitextfield,Ios,Swift,Uitextfield,我使用背景图像集在文本字段上创建自定义清除按钮。 我将其放置在右视图上,但它始终以默认边距放置。我想要的是有一个右边距,例如,8 extension UITextField { func clearButtonWithImage(_ image: UIImage) { let clearButton = UIButton() clearButton.setBackgroundImage(image, for: .normal) clear
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类在选择时更改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
//})
}
}
尝试定位图像边框,但始终保持不变。您应该看看方法。创建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
}
}
我已经为我的textfield使用了一个自定义类,该类显示clearbutton,其中选中了图像并取消了图像设置,我更新了我的问题以查看代码更新了我的答案,您可以尝试一下。