Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Let say I have 3 views

 A|----------|
  | B|-----| |
  |  | C ? | |
  |  |_____| |
  |__________|    

If I have a constraint involving view B and view C.

The documentation suggests adding to view C would be illegal:

The constraint must involve only views that are within scope of the receiving view. Specifically, any views involved must be either the receiving view itself, or a subview of the receiving view. Constraints that are added to a view are said to be held by that view. The coordinate system used when evaluating the constraint is the coordinate system of the view that holds the constraint.

  • Does it matter if I add it to view A or view B?
  • Are there any implications of adding to one superview instead of the other?
  • Are there any convenience implications? (e.g. its easier to manage if all constraints are in one place?)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
277 views
Welcome To Ask or Share your Answers For Others

1 Answer

  • It does not matter if you add it to view A or to view B, so long as they meet the requirements you quoted from the documentation.
  • There are not any implications that I am aware of, the layout is the same either way. The constraints are not necessarily added to the view that you explicitly add them to, according to the comments in the UIView header file (see excerpt below) they are typically installed at the closest ancestor to the views involved in the constraint (and a view is considered to be its own ancestor for this).
  • Neither way is inherently more convenient than the other (unless you don't have a reference to A, in which case it is obviously more convenient to add it to B). It would depend on the setup of your application (what you have outlets for/references to, etc). Given that the constraints are not installed where you explicitly add them, neither way would be more convenient. I would suppose it to be slightly more efficient to add them where the system will install them ultimately, though.

EDIT:

This comment is from UIView.h, above the methods used to install constraints:

/* A constraint is typically installed on the closest common ancestor of the views involved in the constraint. 
 It is required that a constraint be installed on _a_ common ancestor of every view involved.  The numbers in a constraint are interpreted in the coordinate system of the view it is installed on.  A view is considered to be an ancestor of itself.
 */

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...