【问题标题】:Disable editing of UITextField Without disabling subviews [duplicate]在不禁用子视图的情况下禁用 UITextField 的编辑 [重复]
【发布时间】:2018-07-01 22:01:33
【问题描述】:

我有UITextField,我在它的左视图中放了一个UIButton。我想禁用UITextField 的编辑,而我的UIButton 响应点击操作。我尝试了textField.isUserInteractionEnabledtextField.isEnabled,但他们都禁用了我的UIButton。有什么办法吗?我自定义的UITextField 类是这样的

import UIKit

@IBDesignable
class UITextFieldWithButton: UITextField, UITextFieldDelegate {


    private var happyButton: UIButton = UIButton(type: .system)

    @IBInspectable
    var buttonText: String {
        get {
            let string = happyButton.titleLabel!.text!
            let start = string.index(string.startIndex, offsetBy: 2)
            let end = string.endIndex
            return String(happyButton.titleLabel!.text![start..<end])
        }
        set {
            happyButton.setTitle("  " + newValue, for: .normal)
            happyButton.sizeToFit()
            self.leftView = happyButton
            self.leftViewMode = .always
        }
    }


    var isButtonEnable: Bool {
        get {
            return self.isButtonEnable
        }
        set {
            happyButton.isEnabled = newValue
        }
    }
    var buttonDelegate: UITextFieldWithButtonDelegate?

    required override init(frame: CGRect) {
        super.init(frame: frame)
        delegate = self
        happyButton.addTarget(self,action: #selector(pressButton(_:)), for: .touchUpInside)
        happyButton.titleLabel?.font = UIFont(name: (font?.fontName)!, size: (font?.pointSize)!)
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
        delegate = self
        happyButton.addTarget(self,action: #selector(pressButton(_:)), for: .touchUpInside)
        happyButton.titleLabel?.font = UIFont(name: (font?.fontName)!, size: (font?.pointSize)!)
    }

    @objc private func pressButton(_ sender: UIButton){
        if let click = buttonDelegate {
            click.clickOnUITextFieldButton(self)
        }
    }

}

protocol UITextFieldWithButtonDelegate {
    func clickOnUITextFieldButton(_ sender: UITextFieldWithButton)
}

【问题讨论】:

  • UITextField 有一个委托方法 textFieldShouldBeganEditing(_:UITextField) 你应该尝试使用它来禁用编辑而不是禁用整个视图,因为它也会禁用所有其他功能和子视图。
  • @BenOng 我将textFieldShouldBeganEditing(_:UITextField) 的返回值设置为false,它可以工作,谢谢

标签: ios swift uibutton uitextfield custom-controls


【解决方案1】:

“我尝试了 textField.isUserInteractionEnabled 和 textField.isEnabled,但它们都禁用了我的 UIButton”:您的代码运行良好,您可能在 uitextfield 后面添加了按钮,尝试在视图层次结构中将其向前移动

【讨论】:

  • 我尝试了parentView.bringSubview(toFront: childView),但仍然没有点击操作
最近更新 更多