我在代码重用的一些建议。斯威夫特 - 代码重用
我有一个视图控制器(在这个阶段)12 x标签和12 x文本字段。
对于这些标签和字段中的每一个,都有重复的代码行(请参阅下面的注释行)。
我想知道在创建标签和文本字段时重新使用代码行的最佳方法,而不必一直重写它们。
我已经研究过扩展的,创建一个类,并且继承代码的通用行,但我一直打墙。
我已经使用一个类来填充文本字段并理解它是如何工作的,但我似乎无法将其他常用属性添加到该类中。由于
例如:
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“
** 更新 **
感谢所有的意见。
我现在通过添加一个func到我的padding类来重新使用常见的代码行。
不幸的是,文本字段填充不再有效。
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
@Lawliet我一直打的墙都是添加func的东西,但没有得到我期望的结果。根据我对OP的更新。 – K1llarney