Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

ios - Does it matter which superview I add constraints to?

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

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

1 Reply

0 votes
by (71.8m points)
  • 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.
 */

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...