自动布局调整 UI 大小不起作用



我正在尝试让UIView courseView自动布局。我想让 UIView 的比例保持不变并填满,直到最外层的边缘距离超级视图的边缘 15 点。出于某种原因,courseView 会填充整个超级视图(减去 15 个点),并且不会调整大小以适合。所以其中一些没有显示并被切断。

    self.view.addSubview(courseView!)
    let aspectConstraint = NSLayoutConstraint(item: courseView,
        attribute: .Height,
        relatedBy: .Equal,
        toItem: courseView,
        attribute: .Width,
        multiplier: courseView.frame.size.height / courseView.frame.size.width,
        constant: 0.0)
    aspectConstraint.active = true
    let topConstraint = courseView.topAnchor.constraintGreaterThanOrEqualToAnchor(topLayoutGuide.bottomAnchor, constant: 15)
    topConstraint.active = true
    let leadingConstraint = courseView.leadingAnchor.constraintLessThanOrEqualToAnchor(view.leadingAnchor, constant: 15)
    leadingConstraint.active = true
    let trailingConstraint = courseView.trailingAnchor.constraintGreaterThanOrEqualToAnchor(view.trailingAnchor, constant: -15)
    trailingConstraint.active = true
    let bottomConstraint = courseView.bottomAnchor.constraintLessThanOrEqualToAnchor(view.bottomAnchor, constant: -15)
    bottomConstraint.active = true

有什么想法吗?谢谢!

只需在添加约束之前禁用 translatesAutoressizeMaskIntoConstraint,它应该可以正常工作。

courseView.translatesAutoresizingMaskIntoConstraints = false;

顺便说一下,你不需要 aspectConstraint,因为这很可能会破坏 constratints(当我尝试时,它对我确实如此)。

最新更新