简体   繁体   中英

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. 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. In such case inner label of FAQItemView should stretch to the size of 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.

The sample project is available at https://www.dropbox.com/s/u2923l8exqtg3ir/testapp1.zip?dl=0 . Here FAQItemView has red background and the inner label has green background. 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)

Could somebody say what I'm doing wrong?

Thanks in advance.

UPD: Screenshot of view in interface builder

Whoops...

Don't set translatesAutoresizingMaskIntoConstraints = false on your custom view itself .

So, just remove the first line in setup() :

func setup() {
    //translatesAutoresizingMaskIntoConstraints = false

That should fix it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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