重写UILabler的sizeThatFits方法,需要触发两次才会有效果

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了重写UILabler的sizeThatFits方法,需要触发两次才会有效果相关的知识,希望对你有一定的参考价值。

#import "ViewController.h"
@interface SpecialLabel:UILabel
@end

@implementation SpecialLabel

- (CGSize)sizeThatFits:(CGSize)size {

    CGSize s = [super sizeThatFits:size];

    return CGSizeMake(s.width +50, s.height +50);
}
@end

@interface ViewController ()

@property (weak, nonatomic) IBOutlet SpecialLabel *label;

@end

@implementation ViewController

- (IBAction)changeText {
    
    self.label.text = @"fsdgdssssssssssss ";
#if 1
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        [self.label sizeToFit];
    }];
#else
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.001 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
         [self.label sizeToFit];
    });
#endif
    
}

直接这样写不知道为什么不行
self.label.text = @"fsdgdssssssssssss ";  
[self.label sizeToFit];

非得搞个

[NSOperationQueue mainQueue]或者延时,记录一下
 

以上是关于重写UILabler的sizeThatFits方法,需要触发两次才会有效果的主要内容,如果未能解决你的问题,请参考以下文章

sizeThatFits and sizeToFit

用于 UITextView 文本的 iOS 8 sizeThatFits 未返回正确的高度(自动布局)

调整 UIView 的大小以适应 CGPath

如何修复 UIButton sizeToFit/sizeThatFits 的宽度?

UILabel 的 sizeToFit/sizeThatFits 忽略 numberoflines 属性

sizeToFit和sizeThatFits