视图层次结构未针对具有帧初始化程序的init内的约束进行准备

我有一个 UICollectionViewCell 的子类:

class MonthPlanCollectionViewCell: FSCalendarCell {

    override init(frame: CGRect) {
        super.init(frame: frame)

        let stackView = UIStackView()
        stackView.axis = .vertical
        stackView.alignment = .center

        stackView.addArrangedSubview(dayLabel)
        stackView.translatesAutoresizingMaskIntoConstraints = false

        dayLabel.backgroundColor = UIColor.yellow
        plannedTimeLabel.backgroundColor = UIColor.white
        contentView.addSubview(stackView)

        let leading = NSLayoutConstraint(item: stackView, attribute: .leading, relatedBy: .equal, toItem: contentView, attribute: .leading, multiplier: 1, constant: 0)
        let trailing = NSLayoutConstraint(item: stackView, attribute: .trailing, relatedBy: .equal, toItem: contentView, attribute: .trailing, multiplier: 1, constant: 0)
        let centerY = NSLayoutConstraint(item: stackView, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1, constant: 0)

        stackView.addConstraints([leading, trailing, centerY])
    }
}

这个类的用法如下:

func calendar(_ calendar: FSCalendar, cellFor date: Date, at position: FSCalendarMonthPosition) -> FSCalendarCell {

    let cell = calendar.dequeueReusableCell(withIdentifier: MonthPlanCollectionViewCellIdentifier, for: date, at: .current) as! MonthPlanCollectionViewCell


    return cell
}

但每次我有以下问题:

2017-10-03 20:12:31.175147 0200 FieldService [9098:2747076] [LayoutConstraints]视图层次结构不是为约束准备的:id:,常量:0.0当添加到视图时,约束的项必须是后代的该视图(或视图本身) . 如果在组装视图层次结构之前需要解析约束,则会崩溃 . 打破 - [UIView(UIConstraintBasedLayout)_viewHierarchyUnpreparedForConstraint:]进行调试 . 2017-10-03 20:12:31.176687 0200 FieldService [9098:2747076] [LayoutConstraints]视图层次结构未准备好约束 . 约束:id:,常量:0.0容器层次结构:> | > | > | >在容器层次结构中找不到视图:; layer =>

如何使该视图为层次结构做好准备?

回答(2)

2 years ago

尝试先添加约束,然后调用contentView.addSubview(stackView)

2 years ago

您需要将StackView的约束添加到 selfcontentView .

只是改变:

stackView.addConstraints([leading, trailing, centerY])

至:

contentView.addConstraints([leading, trailing, centerY])