gpt4 book ai didi

ios - 在 Swift 中子类化 UITextfield

转载 作者:搜寻专家 更新时间:2023-11-01 06:12:06 24 4
gpt4 key购买 nike

我目前正在我的 View Controller 中初始化相当多的属性,但感觉非常非常困惑。我一直在创建 UITextField,例如:

lazy var passwordTextField: UITextField = {
let textField = UITextField()
let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 30))
textField.leftView = paddingView
textField.leftViewMode = .always
textField.placeholder = "Password"
textField.isSecureTextEntry = true
textField.autocorrectionType = .no
textField.autocapitalizationType = UITextAutocapitalizationType.none
textField.attributedPlaceholder = NSAttributedString(string: "Password", attributes: [NSAttributedString.Key.foregroundColor: UIColor.lightGray])
textField.tintColor = UIColor.white
textField.borderStyle = .none
textField.layer.borderColor = UIColor.white.cgColor
textField.layer.borderWidth = 0.7
textField.delegate = self
textField.textColor = UIColor.white
return textField
}()

每个 UIViewController 我有大约 5 个这样的。我想创建一个 UITextField 类,它基本上是一个输出自定义 UITextField 的工厂。我怎样才能做到这一点?

最佳答案

子类化任何项目都非常容易。只需做类似的事情

class MyTextField: UITextField {
override init(frame: CGRect) {
super.init(frame: frame)
textFieldSetup()
}

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
textFieldSetup()
}

private func textFieldSetup() {
let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 30))
leftView = paddingView
leftViewMode = .always
...
...
//Add the common properties here that you want replicated for every instance
...
...
layer.borderColor = UIColor.white.cgColor
layer.borderWidth = 0.7
textColor = UIColor.white
}
}

然后,您可以创建 MyTextField 实例而不是 UITextField

var passwordTextField: MyTextField!

关于ios - 在 Swift 中子类化 UITextfield,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53953602/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com