gpt4 book ai didi

swift - UITextField rightView 图像和按钮?

转载 作者:行者123 更新时间:2023-11-28 05:57:12 35 4
gpt4 key购买 nike

我在使用 UITextView 时遇到了 2 个问题。我有一个 UIViewController,它有 5 个 UITextFieldUITextField1UITextField2 始终可见,用户无法隐藏。如果用户点击按钮,它会添加(isHidden 属性设置为 false)最多 3 个 UITextFields

每个 UITextFields 都应显示为 .rightView 一个显示左侧字符的自定义 UILabel。除此之外,3 个额外的 UITextFields 还应该添加一个 .rightView 一个 UIButton,当它被点击时它应该为 textField 设置动画.isHidden = true 这样它就会产生删除 UITextField 的错觉。

问题

右 View 的删除 UIButton 不起作用(即不隐藏相应的 UITextField 我不知道为什么。现在当你点击删除 UIButton 它隐藏了奇怪的按钮本身

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

guard let text = textField.text else { return true }
let newLength = text.count + string.count - range.length

let rightView = UIView(frame: CGRect(x: 0, y: 0, width: 55, height: 25))
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
label.font = UIFont(name: Fonts.OpenSans_Light, size: 14)

if textField === thirdChoiceTextField || textField === forthChoiceTextField || textField === fifthChoiceTextField {
let button = UIButton(frame: CGRect(x: rightView.frame.width - 30, y: 0, width: 25, height: 25))
button.setBackgroundImage(UIImage(named: "icon_cancel_dark"), for: .normal)
button.addTarget(self, action: #selector(self.hideTextField(textField:)), for: .touchUpInside)
rightView.addSubview(button)
}

rightView.addSubview(label)
textField.rightView = rightView
textField.rightViewMode = .whileEditing
label.textAlignment = .center

if newLength <= 35 {
label.text = String(50 - newLength)
label.textColor = .lightGray
}
else {
label.text = String(50 - newLength)
label.textColor = UIColor.red
}

return newLength < 50
}


@objc func hideTextField(textField: UITextField) {
if !textField.isHidden {
UIView.animate(withDuration: 0.2) {
textField.isHidden = true
}
}
}

最佳答案

func hideTextField(textField: UITextField)方法中,参数不能是UITextField,应该是UIButton本身,如下,

@objc func hideTextField(_ sender: UIButton) {
...
}

和下一行

button.addTarget(self, action: #selector(self.hideTextField(textField:)), for: .touchUpInside)

将更改为

button.addTarget(self, action: #selector(self.hideTextField(_:)), for: .touchUpInside)

现在你可以像下面那样应用动画了,

@objc func hideTextField(_ sender: UIButton) {
if let field = sender.superview?.superview as? UITextField, !field.isHidden {
UIView.animate(withDuration: 0.2) {
field.isHidden = true
}
}
}

关于swift - UITextField rightView 图像和按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51122856/

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