【问题标题】:UITextField rightView image and button?UITextField rightView 图像和按钮?
【发布时间】:2018-07-01 11:26:33
【问题描述】:

UITextView 有 2 个问题。我有一个 UIViewController 有 5 个 UITextFieldUITextField1UITextField2 始终可见,用户无法隐藏。如果用户点击一个按钮,它会添加(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
        }
    }
}

【问题讨论】:

    标签: swift uibutton uitextfield uitextfielddelegate


    【解决方案1】:

    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 很高兴它有帮助!
    猜你喜欢
    • 2019-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多