我正在尝试获取与安全区域-top相关联的给定视图的topConstraint的引用(例如:附加)。
我创建了一个功能正常但在逻辑上不可靠的函数。
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
}
如果firstItem
或secondItem
是Safe Area.Top
,我该如何比较?
答案 0 :(得分:0)
通过访问constraints
字段所做的操作并不安全。推荐的方法是为约束创建一个IBOutlet