标签:
创建支持AutoLayout的Custom View
AutoLayout 通过使view更加的自组织来减轻controller类的负担。
当实现custom view类时,需要提供足够的信息来使AutoLayout系统能够正确计算和满足约束(Constraints)。
"Leaf-level views, such as buttons, typically know more about what size they should be than does
the code that is positioning them. This is communicated through the method intrinsicContentSize
,
which tells the layout system that there is some content it doesn’t natively understand in a view, and
which provides to the layout system the intrinsic size of that content." Ref[1]
"A view can implement intrinsicContentSize
to return absolute values for its width and height,
or to return NSViewNoInstrinsicMetric
for either or both to indicate that it has no intrinsic metric
for a given dimension." Ref[1]
"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]
Reference
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
3. How to set NSViewShowAlignmentRects?
http://stackoverflow.com/questions/15394033/how-to-set-nsviewshowalignmentrects
iOS.AutoLayout.2.CustomViewWithAutoLayout
标签:
原文地址:http://www.cnblogs.com/cwgk/p/4508303.html