2

I have UITextField and I put a UIButton in the left view of it. I want to disable editing of UITextField while my UIButton response to on click action. I tried textField.isUserInteractionEnabled and also textField.isEnabled but both of them also disable my UIButton. is there any way to do this? my custom UITextField class is like this

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)
}
Karo
  • 273
  • 4
  • 16
  • 2
    UITextField have a delegate method `textFieldShouldBeganEditing(_:UITextField)` you should trying using that to disable editing instead of disabling the entire view since it will also disable all other features and subviews. – Ben Ong Jan 23 '18 at 06:58
  • @BenOng I set the return of `textFieldShouldBeganEditing(_:UITextField)` to false and it works, thanks – Karo Jan 23 '18 at 07:01
  • https://stackoverflow.com/questions/9116969/how-to-disable-uitextfield-editing-but-still-accept-touch – Code Hunterr Jan 23 '18 at 10:05

1 Answers1

1

"I tried textField.isUserInteractionEnabled and also textField.isEnabled but both of them also disable my UIButton" :your code is working fine you might have added button behind uitextfield try to move it forward in view hierarchy

CazzyTheCoder
  • 101
  • 1
  • 7