【问题标题】:Create UITextField in different class doesn't allow to type在不同的类中创建 UITextField 不允许输入
【发布时间】:2018-05-15 17:35:05
【问题描述】:

我在一个单独的类中有这个函数:

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 上写字?

【问题讨论】:

  • 您确定只是将代理设置为 nil 吗?我以为你必须将文本字段委托设置为 vc。

标签: swift uitextfield swift4


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2020-03-09
    • 2012-10-08
    • 1970-01-01
    • 1970-01-01
    • 2018-11-13
    • 1970-01-01
    • 2017-08-30
    • 2012-12-19
    • 1970-01-01
    相关资源
    最近更新 更多