我對程式化 UI 幾乎是新手。
我一直在為我的專案創建一些自定義 UI 組件,但是當我檢查人們的專案時,我發現我創建 UI 組件的方式與他們的不同。
這些代碼完全實作了相同的功能,但方式不同。
這兩個代碼有什么區別?
func makeLabel(withAlignment alignment: NSTextAlignment,
withFontSize fontSize: CGFloat) -> UILabel {
let label = UILabel()
label.textAlignment = alignment
label.font = UIFont.systemFont(ofSize: fontSize,
weight: .bold)
label.textColor = .label
label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = 0.9
label.lineBreakMode = .byTruncatingTail
label.translatesAutoresizingMaskIntoConstraints = false
return label
}
init(textAlignment: NSTextAlignment,
fontSize: CGFloat) {
super.init(frame: .zero)
self.textAlignment = textAlignment
self.font = UIFont.systemFont(ofSize: fontSize,
weight: .bold)
}
private func configure() {
self.textColor = .label
self.adjustsFontSizeToFitWidth = true
self.minimumScaleFactor = 0.9
self.lineBreakMode = .byTruncatingTail
self.translatesAutoresizingMaskIntoConstraints = false
}
在我的 VC 中呼叫它們是相同的方式。
所以問題是哪種方式更適合我創建自定義 UI?這兩種技術有什么優缺點嗎?
uj5u.com熱心網友回復:
第一個只是一個助手,您創建了一個回傳UILabel的函式
第二個是CustomView,它可以包含一個標簽,但它也可以由幾個元素組成,例如一個影像 標簽
在自定義視圖中,您還可以覆寫 drawRect 之類的方法或添加一些其他組件:例如
var isSelected {
didSet {
//do something
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/466616.html
上一篇:標題WooCommerce網關
