建立支持AutoLayout的Custom Viewhtml
AutoLayout 經過使view更加的自組織來減輕controller類的負擔。ios
當實現custom view類時,須要提供足夠的信息來使AutoLayout系統可以正確計算和知足約束(Constraints)。git
"Leaf-level views, such as buttons, typically know more about what size they should be than doesgithub
the code that is positioning them. This is communicated through the method intrinsicContentSize
,app
which tells the layout system that there is some content it doesn’t natively understand in a view, andide
which provides to the layout system the intrinsic size of that content." Ref[1]ui
"A view can implement intrinsicContentSize
to return absolute values for its width and height,this
or to return NSViewNoInstrinsicMetric
for either or both to indicate that it has no intrinsic metricspa
for a given dimension." Ref[1]3d
"Remember that you can also set constant width or height constraints on any view, and you don't
need to override instrinsicContentSize if these dimensions won't be changing with changing view content."
UIView的instrinsicContentSize默認實現是返回(UIViewNoIntrinsicMetric, UIViewNoIntrinsicMetric)。
當Custom View的內在Size發生變化時通知AutoLayout,經過方法invalidateIntrinsicContentSize來通知AutoLayout。
Constraints do not actually relate the frames of the views, rather they relate the "alignment rects" of views.
1 /* Set the NSUserDefault UIViewShowAlignmentRects to YES to see alignment rects drawn. 2 */ 3 - (CGRect)alignmentRectForFrame:(CGRect)frame NS_AVAILABLE_IOS(6_0); 4 - (CGRect)frameForAlignmentRect:(CGRect)alignmentRect NS_AVAILABLE_IOS(6_0); 5 6 /* override this if the alignment rect is obtained from the frame by insetting each edge by a fixed amount.
This is only called by alignmentRectForFrame: and frameForAlignmentRect:. 7 */ 8 - (UIEdgeInsets)alignmentRectInsets NS_AVAILABLE_IOS(6_0);
在開發時使"alignment rects"顯示出來:
"
In Debug, the Arguments tab, Arguments passed on launch, click the plus button and enter this:
-UIViewShowAlignmentRects YES
(for iOS projects)
or-NSViewShowAlignmentRects YES
(for Mac OS projects)
You should have a bunch of yellow outlines when you run" Ref[3]
Ref[2]
1. Implementing a Custom View to Work with Auto Layout
2. Custom Views with Auto Layout
http://www.electricpeelsoftware.com/2013/05/08/custom-views-with-auto-layout.html
https://github.com/peterstuart/AutoLayoutExample
3. How to set NSViewShowAlignmentRects?
http://stackoverflow.com/questions/15394033/how-to-set-nsviewshowalignmentrects
4. Advanced Auto Layout Toolbox (AAAA+)
https://www.objc.io/issues/3-views/advanced-auto-layout-toolbox/