【发布时间】:2017-07-28 06:51:23
【问题描述】:
我正在寻求一些关于代码重用的建议。
我有一个视图控制器(在这个阶段)有 12 个标签和 12 个文本字段。
对于每个标签和字段,都有重复的代码行(请参阅下面的注释行)。
我想知道在创建标签和文本字段时重复使用代码行的最佳方法,而不是一直重写它们。
我已经研究过扩展,创建了一个类,还继承了常见的代码行,但我一直碰壁。
我已经使用了一个类来填充文本字段并了解它是如何工作的,但我似乎无法将其他常见属性添加到该类中。谢谢
示例:
let LabelA = UILabel()
// LabelA.backgroundColor = .clear
// LabelA.widthAnchor.constraint(equalToConstant: 150).isActive = true
// LabelA.font = LabelA.font.withSize(18)
// LabelA.textAlignment = .left
LabelA.text = “This is my 1st label of 12“
let LabelB = UILabel()
// LabelB.backgroundColor = .clear
// LabelB.widthAnchor.constraint(equalToConstant: 150).isActive = true
// LabelB.font = LabelB.font.withSize(18)
// LabelB.textAlignment = .left
LabelB.text = “This is my 2nd label of 12“
let LabelC = UILabel()
// LabelC.backgroundColor = .clear
// LabelC.widthAnchor.constraint(equalToConstant: 150).isActive = true
// LabelC.font = LabelC.font.withSize(18)
// LabelC.textAlignment = .left
LabelC.text = “This is my 3rd label of 12“
** 更新 **
感谢所有的cmets。
我现在通过向我的填充类添加一个 func 来重用常见的代码行。
很遗憾,文本字段填充不再起作用。
class PaddedTextField: UITextField {
let padding = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5);
override func textRect(forBounds bounds: CGRect) -> CGRect {
return UIEdgeInsetsInsetRect(bounds, padding)
}
override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
return UIEdgeInsetsInsetRect(bounds, padding)
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
return UIEdgeInsetsInsetRect(bounds, padding)
}
func createText(with text: String) -> UITextField {
let txtField = UITextField()
txtField.backgroundColor = .clear
txtField.widthAnchor.constraint(equalToConstant: 250).isActive = true
txtField.layer.borderWidth = 1
txtField.layer.borderColor = UIColor(r: 203, g: 203, b: 203).cgColor
txtField.layer.cornerRadius = 5
txtField.layer.masksToBounds = true
txtField.placeholder = text
txtField.isEnabled = true
return txtField
}
}
所以,这行代码在没有添加字段填充的情况下工作......
let textFieldA = PaddedTextField().createText(with: "placeholder text...")
...这适用于字段填充,但不能重复使用常见的代码行。
let textFieldB = PaddedTextField()
textFieldB.backgroundColor = .clear
textFieldB.widthAnchor.constraint(equalToConstant: 250).isActive = true
textFieldB.layer.borderWidth = 1
textFieldB.layer.borderColor = UIColor(r: 203, g: 203, b: 203).cgColor
textFieldB.layer.cornerRadius = 5
textFieldB.layer.masksToBounds = true
textFieldB.placeholder = "textFieldB placeholder text..."
textFieldB.isEnabled = true
我不确定我有哪些错误/不明白的部分。谢谢。
【问题讨论】:
-
“子类化常见的代码行,但我一直在碰壁”。墙壁是什么?
-
@Lawliet 我一直在打的墙是添加 func 之类的东西,但没有得到我期望的结果。根据我对 OP 的更新。
标签: swift uitextfield uilabel