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的尺寸改變,行數也改變了,根據最新的尺寸可添加相應尺寸的背景圖片。
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM