首页 > 解决方案 > 是否可以创建 UITextfield 扩展,然后将其作为函数调用?谢谢你

问题描述

我想为多个字段重用这组代码

    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 的最佳实践

标签: iosxcodeuikitswift5

解决方案


如果您可以创建扩展名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

推荐阅读