我想創建一個自定義UIView,比如說TestLabelView,它包含一個邊距為 16px 的標簽。
它看起來像這樣:

以下是我嘗試創建此自定義UIView并在視圖控制器中實體化它的方法:
測驗標簽視圖
class TestLabelView: UIView {
private var label = UILabel()
var text: String = "" { didSet { updateUI() } }
override init(frame: CGRect) {
super.init(frame: frame)
internalInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
internalInit()
}
private func internalInit() {
backgroundColor = .red
label.numberOfLines = 0
translatesAutoresizingMaskIntoConstraints = false
addSubview(label)
}
private func updateUI() {
label.text = text
NSLayoutConstraint(item: label,
attribute: .leading,
relatedBy: .equal,
toItem: self,
attribute: .leading,
multiplier: 1,
constant: 24).isActive = true
NSLayoutConstraint(item: self,
attribute: .trailing,
relatedBy: .equal,
toItem: label,
attribute: .trailing,
multiplier: 1,
constant: 24).isActive = true
NSLayoutConstraint(item: label,
attribute: .top,
relatedBy: .equal,
toItem: self,
attribute: .top,
multiplier: 1,
constant: 24).isActive = true
NSLayoutConstraint(item: self,
attribute: .bottom,
relatedBy: .equal,
toItem: label,
attribute: .bottom,
multiplier: 1,
constant: 24).isActive = true
setNeedsUpdateConstraints()
}
}
視圖控制器
class ViewController: UIViewController {
@IBOutlet weak var testLabelView: TestLabelView?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
testLabelView?.text = "This is a test view with a test label, contained in multiple lines"
}
}
在故事板中

我設定了一個占位符固有大小來消除情節提要錯誤,并且底部邊距大于等于24px,因此應根據內容大小設定視圖高度
但是,這樣做,我看不到標簽出現。我究竟做錯了什么?

謝謝您的幫助
uj5u.com熱心網友回復:
您可以嘗試使用此代碼TestLabelView查看
class TestLabelView: UIView {
private var label : UILabel = {
let l = UILabel()
l.translatesAutoresizingMaskIntoConstraints = false
l.numberOfLines = 0
return l
}()
var text: String = "" { didSet { self.label.text = self.text } }
override init(frame: CGRect) {
super.init(frame: frame)
internalInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
internalInit()
}
private func internalInit() {
backgroundColor = .red
translatesAutoresizingMaskIntoConstraints = false
addSubview(label)
setConstraints()
}
private func setConstraints() {
NSLayoutConstraint.activate([
self.label.topAnchor.constraint(equalTo: self.topAnchor, constant: 16),
self.label.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 16),
self.label.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -16),
self.label.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -16),
])
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/441313.html
