【发布时间】:2018-07-01 22:01:33
【问题描述】:
我有UITextField,我在它的左视图中放了一个UIButton。我想禁用UITextField 的编辑,而我的UIButton 响应点击操作。我尝试了textField.isUserInteractionEnabled 和textField.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