我在一个单独的类中有此功能:

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?


返回错误:


  “未拥有”仅适用于类和类绑定的协议类型,
  不是“ UITextFieldDelegate?”


我怎么不能在我的UITextfield上写?

最佳答案

您需要创建一个带有强引用的静态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
}

10-05 20:26
查看更多