ios - 是否可以创建 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 的最佳实践
解决方案
如果您可以创建扩展名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
推荐阅读
- javascript - JavaScript 代码是否转换为汇编代码?
- mongodb - MongoDb 用户缺少操作“删除”,但在继承角色中启用
- reactjs - 如何将客户端从 ApolloProvider 传递到也采用其他道具的组件?
- sql - SQL:添加逻辑以在选择最大值时处理平局
- javascript - 在 JS 中优化一个 deep 和 map 函数
- javascript - ReactRouter:传入数据/对象
- java - 具有递归的可变数据类型的乘积
- ssl - TLS 的 WebSocketpp 握手问题
- c - C中函数typedef的前向声明
- assembly - Intel 8086 程序集 - 间接寻址和比较指令 (MASM)