0
votes

I have a subclass of 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])
    }
}

This class is used like this:

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
}

But everytime I have following issue:

2017-10-03 20:12:31.175147+0200 FieldService[9098:2747076] [LayoutConstraints] The view hierarchy is not prepared for the constraint: id: , constant: 0.0 When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled. Break on -[UIView(UIConstraintBasedLayout) _viewHierarchyUnpreparedForConstraint:] to debug. 2017-10-03 20:12:31.176687+0200 FieldService[9098:2747076] [LayoutConstraints] View hierarchy unprepared for constraint. Constraint: id: , constant: 0.0 Container hierarchy: > | > | > | > View not found in container hierarchy: ; layer = >

What to do to make that view prepared for hierarchy?

2

2 Answers

0
votes

Try to first add constraints and then call contentView.addSubview(stackView)

0
votes

You need to add the StackView's constraints either to self or to the contentView.

Just change:

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

to:

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