У меня 2 проблемы с UITextView. У меня есть UIViewController с 5 UITextField. UITextField1 и UITextField2 всегда видны и не могут быть скрыты пользователем. Если пользователь нажимает кнопку, он добавляет (для свойства isHidden установлено значение false) еще до 3 UITextFields.
Каждый из этих UITextFields должен отображать как .rightView собственный UILabel, который показывает левые символы. В дополнение к этому, 3 дополнительных UITextFields должны также добавить в качестве .rightViewUIButton, который при нажатии должен оживлять 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
}
}
}





В методе 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
}
}
}
@Dani Рад, что это помогло!
Отлично! Вот что я пытался сделать! Спасибо