[英]Interface builder doesn't stretch subviews of custom view
我使用一個內部UILabel創建了自定義視圖(FAQItemView),該視圖被限制在Superview的四個側面。 這是此視圖的源代碼:
import UIKit
@IBDesignable class FAQItemView: UIView {
var questionLabel: UILabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup() {
translatesAutoresizingMaskIntoConstraints = false
addSubview(questionLabel)
questionLabel.translatesAutoresizingMaskIntoConstraints = false
questionLabel.textColor = UIColor.black
questionLabel.textAlignment = .center
questionLabel.numberOfLines = 0
questionLabel.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
questionLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
questionLabel.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
questionLabel.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
questionLabel.text = "question"
questionLabel.backgroundColor = UIColor.green
}
}
我已經在Interface Builder中添加了FAQItemView,並將其寬度限制為200px。 在這種情況下,FAQItemView的內部標簽應擴展到FAQItemView的大小。 當我運行應用程序時,一切都很好,但是在Interface Builder中,標簽以其默認(本征)大小位於容器的左側。
示例項目可從https://www.dropbox.com/s/u2923l8exqtg3ir/testapp1.zip?dl=0獲得 。 此處,FAQItemView具有紅色背景,內部標簽具有綠色背景。 在運行時,紅色是不可見的,因為標簽具有綠色背景,但是在Interface Builder中,紅色也是可見的(在帶有綠色背景的標簽右側)
有人可以說我做錯了嗎?
提前致謝。
哎呦...
不要在自定義視圖本身上設置translatesAutoresizingMaskIntoConstraints = false
。
因此,只需刪除setup()
的第一行:
func setup() {
//translatesAutoresizingMaskIntoConstraints = false
那應該解決它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.