简体   繁体   English

界面生成器不会拉伸自定义视图的子视图

[英]Interface builder doesn't stretch subviews of custom view

I've created custom view (FAQItemView) with one inner UILabel, that is constrained to four sides of superview. 我使用一个内部UILabel创建了自定义视图(FAQItemView),该视图被限制在Superview的四个侧面。 Here is the source code of this view: 这是此视图的源代码:

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
    }
}

I've added FAQItemView in Interface Builder and constrained its width to 200px. 我已经在Interface Builder中添加了FAQItemView,并将其宽度限制为200px。 In such case inner label of FAQItemView should stretch to the size of FAQItemView. 在这种情况下,FAQItemView的内部标签应扩展到FAQItemView的大小。 All is ok when i run app, but in Interface Builder label is positioned in the left side of container with its default (intrinsic) size. 当我运行应用程序时,一切都很好,但是在Interface Builder中,标签以其默认(本征)大小位于容器的左侧。

The sample project is available at https://www.dropbox.com/s/u2923l8exqtg3ir/testapp1.zip?dl=0 . 示例项目可从https://www.dropbox.com/s/u2923l8exqtg3ir/testapp1.zip?dl=0获得 Here FAQItemView has red background and the inner label has green background. 此处,FAQItemView具有红色背景,内部标签具有绿色背景。 In runtime the red color isn't visible because label has green background but in Interface Builder red color is also visible (to the right of label with green background) 在运行时,红色是不可见的,因为标签具有绿色背景,但是在Interface Builder中,红色也是可见的(在带有绿色背景的标签右侧)

Could somebody say what I'm doing wrong? 有人可以说我做错了吗?

Thanks in advance. 提前致谢。

UPD: Screenshot of view in interface builder UPD:界面构建器中视图的屏幕截图

Whoops... 哎呦...

Don't set translatesAutoresizingMaskIntoConstraints = false on your custom view itself . 不要在自定义视图本身上设置translatesAutoresizingMaskIntoConstraints = false

So, just remove the first line in setup() : 因此,只需删除setup()的第一行:

func setup() {
    //translatesAutoresizingMaskIntoConstraints = false

That should fix it. 那应该解决它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM