XiaoKL

iOS.AutoLayout.2.CustomView-with-AutoLayout

Custom View Which Support AutoLayout

创建支持AutoLayout的Custom View

AutoLayout 通过使view更加的自组织来减轻controller类的负担。

当实现custom view类时,需要提供足够的信息来使AutoLayout系统能够正确计算和满足约束(Constraints)。

 

1. 为Custom View指定 intrinsic size (内在的/固有的 size)

"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)。

2. 通知AutoLayout关于 intrinsic size 的变化

当Custom View的内在Size发生变化时通知AutoLayout,通过方法invalidateIntrinsicContentSize来通知AutoLayout。

3. AutoLayout操作UIView的"Alignement Rects"而非frame

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 the Xcode menu Product -> Scheme -> Edit Scheme (or ⌘-<)
  • 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'll need the dash at the start
  • Tap OK

You should have a bunch of yellow outlines when you run" Ref[3]

 

 

 

 

 

 

 

 

 

4. Demo for Mac OS X App

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 

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/

 

posted on 2015-05-16 18:46  XiaoKL  阅读(512)  评论(0编辑  收藏  举报

导航