UITextField rightView изображение и кнопка? - PullRequest
0 голосов
/ 01 июля 2018

У меня 2 проблемы с UITextView. У меня есть UIViewController, который имеет 5 UITextField. UITextField1 и UITextField2 всегда видимы и не могут быть скрыты пользователем. Если пользователь нажимает на кнопку, он добавляет (для свойства isHidden установлено значение false) еще до 3 UITextFields.

Каждый из этих UITextFields должен отображать как .rightView пользовательский UILabel, который показывает левые символы. В дополнение к этому, 3 дополнительных UITextFields также должны добавить как .rightView a 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
        }
    }
}

1 Ответ

0 голосов
/ 01 июля 2018

В методе 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
        }
    }
 }
...