我在UITextView上有两个问题。我有一个UIViewController,它有5 UITextField。UITextField1和UITextField2总是可见的,不能被用户隐藏。如果用户点击按钮,它会添加(isHidden属性设置为false),最多再添加3个UITextFields。
这些UITextFields中的每一个都应该以.rightView的形式显示一个显示左字符的自定义UILabel。除此之外,另外3个UITextFields还应该作为一个.rightView添加一个UIButton,当它被点击时,它应该将textField.isHidden = true动画化,这样它就会产生一个错觉,即它删除了UITextField。
问题
删除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
}
}
}发布于 2018-07-01 12:04:19
在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
}
}
}https://stackoverflow.com/questions/51122856
复制相似问题