是否可以创建 UITextfield Extensions 然后将其作为函数调用?谢谢你

is it possible to create UITextfield Extensions and then call it as a function?? thank you

我想对多个字段重用这段代码

    private let passwordField: UITextField = {
        let field = UITextField()
        field.isSecureTextEntry = true
        field.placeholder = "Password...."
        field.returnKeyType = .continue
        field.leftViewMode = .always
        field.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 0))
        field.autocapitalizationType = . none
        field.autocorrectionType = .no
        field.layer.masksToBounds = true
        field.layer.cornerRadius = constansts.cornerRadius
        field.backgroundColor = .secondarySystemBackground
        return field
        
    }()

问题)我有一个带有 5 个文本字段的注册屏幕 不是为每个都编写所有内容,是否可以有扩展或函数以便我可以进行函数调用??

或 ) 是否有重用 UIComponents 的最佳实践

如果您可以为 UIViewController 创建扩展并简单地使用下面的代码片段并避免代码行数。

extension UIViewController {
    func createPasswordTextField(frame: CGRect) -> UITextField {
        let field = UITextField()
        field.isSecureTextEntry = true
        field.placeholder = "Password...."
        field.returnKeyType = .continue
        field.leftViewMode = .always
        field.leftView = UIView(frame: frame)
        field.autocapitalizationType = . none
        field.autocorrectionType = .no
        field.layer.masksToBounds = true
        field.layer.cornerRadius = constansts.cornerRadius
        field.backgroundColor = .secondarySystemBackground
        return field
    }
  }

如果您使用 textField 常量而不是为 UITextField 创建扩展,如下所示:

extension UITextField {
    func sameUI() { 
      self.isSecureTextEntry = true
      self.placeholder = "Password...."
      self.returnKeyType = .continue
      self.leftViewMode = .always
      self.leftView = UIView(frame: frame)
      self.autocapitalizationType = . none
      self.autocorrectionType = .no
      self.layer.cornerRadius = constansts.cornerRadius
      self.backgroundColor = .secondarySystemBackground
    }
}

使用:

let txt = self.createPasswordTextField(.zero) //create and return textField
txt.sameUI() //apple same configuration in your textField