Fork me on GitHub

UIView的sizeToFit:和fitSize方法

- (CGSize)sizeThatFits:(CGSize)size;     // return 'best' size to fit given size. does not actually resize view. Default is return existing view size

- (void)sizeToFit;                       // calls sizeThatFits: with current view bounds and changes bounds size.


sizeThatFits:

 

Asks the view to calculate and return the size that best fits its subviews.

- (CGSize)sizeThatFits:(CGSize)size
Parameters
size

The current size of the receiver.

Return Value

A new size that fits the receiver’s subviews.

Discussion

The default implementation of this method returns the size portion of the view’s bounds rectangle. Subclasses can override this method to return a custom value based on the desired layout of any subviews. For example, a UISwitch object returns a fixed size value that represents the standard size of a switch view, and a UIImageView object returns the size of the image it is currently displaying.

This method does not resize the receiver.

Availability
  • Available in iOS 2.0 and later.


sizeToFit

Resizes and moves the receiver view so it just encloses its subviews.

- (void)sizeToFit
Discussion

Call this method when you want to resize the current view so that it uses the most appropriate amount of space. Specific UIKit views resize themselves according to their own internal needs. In some cases, if a view does not have a superview, it may size itself to the screen bounds. Thus, if you want a given view to size itself to its parent view, you should add it to the parent view before calling this method.

You should not override this method. If you want to change the default sizing information for your view, override the sizeThatFits: instead. That method performs any needed calculations and returns them to this method, which then makes the change.

Availability
  • Available in iOS 2.0 and later.
个人应用:
- (void)sizeToFit得到最适合当前字数的尺寸,
1   新建一个UILabel *label,尺寸CGRectMake(10,10,150,20);    [label setNumberOfLine:1];    [label setBackgroundColor:[UIColor clearColor];
2   之后从键盘输入到UITextField中一定数量文字,将文字赋值给label;
3   对label使用 方法   - (void)sizeToFit;   当前label的尺寸改变,行数也改变了,根据最新的尺寸可添加相应尺寸的背景图片。
 

posted on 2012-03-23 17:30  pengyingh  阅读(21714)  评论(0编辑  收藏  举报

导航