gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 06:08:20 26 4
gpt4 key购买 nike

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

关于ios - iOS 中自定义清除按钮的右边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47534040/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com