获取顶部约束的参考

时间:2019-05-08 07:58:57

标签: ios swift autolayout constraints safearealayoutguide

我正在尝试获取与安全区域-top相关联的给定视图的topConstraint的引用(例如:附加)。

enter image description here

我创建了一个功能正常但在逻辑上不可靠的函数。

func getSafeAreaTopConstraint(view: UIView, in targetView: UIView) -> NSLayoutConstraint? {
    let constraints = targetView.constraints.filter({ $0.firstItem as? UIView == view || $0.secondItem as? UIView == view })
    return constraints.filter({ $0.firstAttribute == .top || $0.secondAttribute == .top }).first
}

我想创建一个比较如下的函数

func getSafeAreaTopConstraint(view: UIView, in targetView: UIView) -> NSLayoutConstraint? {
    let constraints = targetView.constraints.filter({ ($0.firstItem as? UIView == view && $0.secondItem == SafeArea.Top) || ($0.secondItem as? UIView == view && $0.firstItem == SafeArea.Top) })
    return constraints.filter({ $0.firstAttribute == .top || $0.secondAttribute == .top }).first
}

如果firstItemsecondItemSafe Area.Top,我该如何比较?

1 个答案:

答案 0 :(得分:0)

通过访问constraints字段所做的操作并不安全。推荐的方法是为约束创建一个IBOutlet