[英]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.