談談 sizeToFit 與 sizeThatFit

先看看蘋果官方文檔對這連個的方法的解釋:學習

- (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: 會計算出最優的 size 可是不會改變 本身的 size,而 sizeToFit: 會計算出最優的 size 並且會改變本身的 size。那麼二者的聯繫是什麼呢?code

實際上,當調用 sizeToFit 後會調用 sizeThatFits 方法來計算 UIView 的 bounds.size 而後改變 frame.size。也就是說,其實咱們也能夠不使用 [ label sizeToFit] 來計算 label 內容的 size ,首先調用 sizeThatFits 方法或者一個 CGSize 而後改變 label.frame.size 就能夠獲得 [label sizeToFit]同樣的效果。下面用實例加以說明:blog

UILabel *testLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 100, 20)];
    testLabel.text = @"歡迎關注黃飛的csdn博客";
    testLabel.font = [UIFont systemFontOfSize:14];
    testLabel.textAlignment=NSTextAlignmentCenter;
    //使用sizeThatFit計算lable大小
    CGSize sizeThatFit=[testLabel sizeThatFits:CGSizeZero];
    NSLog(@"%f-----%f", sizeThatFit.width, sizeThatFit.height);
    NSLog(@"%f-----%f", testLabel.frame.size.width, testLabel.frame.size.height);
    // 調用sizeToFit
    [testLabel sizeToFit];
    NSLog(@"%f-----%f", testLabel.frame.size.width, testLabel.frame.size.height);
    testLabel.textColor=[UIColor blackColor];
    testLabel.backgroundColor=[UIColor yellowColor];
    [self.view addSubview:testLabel];

運行結果以下所示:
這裏寫圖片描述圖片

這也驗證了官方的對其的解釋:sizeThatFits: 會計算出最優的 size 可是不會改變 本身的 size,而 sizeToFit: 會計算出最優的 size 並且會改變本身的 size。文檔

上述說的是 Label 單行顯示時的情形,當 Label 文本較長以致於不能單行顯示時,二者也是有區別的。博客

sizeThatFit:it

UILabel *testLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 50, 20)];
    testLabel.text = @"歡迎關注黃飛的csdn博客,這裏有你想要的東西,歡迎關注!!";
    testLabel.font = [UIFont systemFontOfSize:14];
    testLabel.textAlignment=NSTextAlignmentCenter;
    testLabel.numberOfLines = 0;
    //使用sizeThatFit計算lable大小
    CGSize sizeThatFit = [testLabel sizeThatFits:CGSizeZero];
    testLabel.frame    = CGRectMake(testLabel.frame.origin.x, testLabel.frame.origin.y, sizeThatFit.width, sizeThatFit.height);

    testLabel.textColor=[UIColor blackColor];
    testLabel.backgroundColor=[UIColor yellowColor];
    [self.view addSubview:testLabel];

sizeToFit:class

UILabel *testLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 100, 20)];
    testLabel.text = @"歡迎關注黃飛的csdn博客,這裏有你想要的東西,歡迎關注!!";
    testLabel.font = [UIFont systemFontOfSize:14];
    testLabel.textAlignment=NSTextAlignmentCenter;
    testLabel.numberOfLines = 0;

    [testLabel sizeToFit];

    testLabel.textColor=[UIColor blackColor];
    testLabel.backgroundColor=[UIColor yellowColor];
    [self.view addSubview:testLabel];

二者的效果對好比下:
這裏寫圖片描述test

當設置多行顯示時,二者又體現出區別,sizeThatFits並不會折行顯示,sizeToFits會在設置的寬度內這行顯示。這實際上又從另外一方面驗證了官方的解釋。object

知其然,更要知其因此然,學習沒有捷徑,堅持和專研是硬道理,多分享則樂趣無窮!歡迎關注後續博文!

相關文章
相關標籤/搜索