我在一个单独的类中有这个功能:
public static func TextField(x:CGFloat=0, y:CGFloat=0, width: CGFloat=0, height: CGFloat=0, placeholder: String="", fontSize:CGFloat=15, fontColor: UIColor=UIColor.black, fontWeight:UIFont.Weight=UIFont.Weight.light ,passwordField: Bool = false) -> UITextField{
weak var delegate: UITextFieldDelegate?
let textfield = UITextField(frame: CGRect(x: x, y: y, width: width, height: height))
textfield.placeholder = placeholder
textfield.textColor = fontColor
textfield.font = UIFont.systemFont(ofSize: fontSize, weight: fontWeight)
textfield.isSecureTextEntry = passwordField
textfield.isUserInteractionEnabled = true
textfield.autocorrectionType = UITextAutocorrectionType.no
textfield.keyboardType = UIKeyboardType.default
textfield.contentVerticalAlignment = UIControlContentVerticalAlignment.center
textfield.delegate = delegate
return textfield
}
它正确地创建了UITextField
,并且具有我预期的正确行为,我无法输入任何UITextFields
。
另外,我尝试添加一个单独的类:
class MyTextFieldDelegate : NSObject, UITextFieldDelegate{
func textFieldShouldReturn(textField: UITextField!) -> Bool{
textField.resignFirstResponder()
return true;
}
}
但是没有用。 另外,阅读this StackOverflow post
unowned(unsafe) var delegate: UITextFieldDelegate?
返回错误:
'unowned'可能只适用于类和类绑定协议类型, 不是'UITextFieldDelegate?'
我怎么不能在我的UITextfield
上写字?
答案 0 :(得分:0)
你需要创建一个带有强引用的静态let变量,以便在你的工厂函数中使用它(遵循Swift名称约定并调用它,例如makeDefaultTextField),并且只是为了在分配你给出的委托时更清楚负责管理您班级的委托方法:
static let myDelegate = MyTextFieldDelegate()
public static func makeDefaultTextField(x:CGFloat=0, y:CGFloat=0, width: CGFloat=0, height: CGFloat=0, placeholder: String="", fontSize:CGFloat=15, fontColor: UIColor=UIColor.black, fontWeight:UIFont.Weight=UIFont.Weight.light ,passwordField: Bool = false) -> UITextField {
let textfield = UITextField(frame: CGRect(x: x, y: y, width: width, height: height))
//....
textField.delegate = myDelegate
}
如果您想在ViewController中管理委托方法(强烈建议),您可以这样做,例如:
class YourViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let txtField = YourClass.makeDefaultTextField()
txtField.delegate = self
}
}
extension YourViewController: UITextFieldDelegate {
//call here the methods
}