我有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 =>
如何使该视图为层次结构做好准备?
答案 0 :(得分:0)
尝试先添加约束,然后调用contentView.addSubview(stackView)
答案 1 :(得分:0)
您需要将StackView的约束添加到self
或contentView
。
只需改变:
stackView.addConstraints([leading, trailing, centerY])
为:
contentView.addConstraints([leading, trailing, centerY])