我在代碼重用的一些建議。斯威夫特 - 代碼重用
我有一個視圖控制器(在這個階段)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