0

I am trying to get the reference of topConstraint (eg: attached) of a given view, associated with safe area - top.

enter image description here

I have created a function which works fine, but, logically not reliable.

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
}

I would like to create a function which compares as follows

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
}

How do I compare if the firstItem or secondItem is Safe Area.Top?

iOS
  • 3,526
  • 3
  • 37
  • 82
  • 2
    IBOUtlet, make a conection with your code, you can also get it by constraint identifier – Reinier Melian May 08 '19 at 08:02
  • @ReinierMelian I have attached the screenshot for an understanding. I m trying to get it programmatically for any given view. – iOS May 08 '19 at 08:04
  • 1
    You need to add the constraint in the storyboard or xib manually anyway right? – Reinier Melian May 08 '19 at 08:08
  • I have to do some adjustment in topConstraint of given view associated with `SafeArea.Top`. Thats why I am trying to get the reference. – iOS May 08 '19 at 08:13
  • I think is pointless this kind of function if you want to have a reference to all your views top constraints, you need to put an identifier on it or make it a Outlet when is created manually in the storyboard, if you are making this change later on your code or someone's code this will be painful but is the only way, or at least the only way i know to do it, firstAttribute and secondAttribute is not reliable for comparison – Reinier Melian May 08 '19 at 08:18
  • btw if you find another reliable way please post it as answer, will be helpful and interesting happy coding – Reinier Melian May 08 '19 at 08:20

1 Answers1

0

What you are doing, by accessing the constraints field is not safe. The recommended approach is creating an IBOutlet for the constraint