Dynamically resize label in iOS 7

后端 未结 4 1937
旧巷少年郎
旧巷少年郎 2020-12-09 14:19

In iOS 6, I am using :

CGSize labelSize = [self.text sizeWithFont:self.font constrainedToSize:size lineBreakMode:self.lineBreakMode];
self.frame = CGRectMake         


        
4条回答
  •  失恋的感觉
    2020-12-09 14:26

    Without more details on why it doesn't work, my guess would be that you need to use the option NSStringDrawingUsesLineFragmentOrigin in order for it to become a drop-in replacement for the old sizeWithFont:, like this:

    NSString *text = ...;
    CGFloat width = ...;
    UIFont *font = ...;
    NSAttributedString *attributedText =
        [[NSAttributedString alloc]
            initWithString:text
            attributes:@
            {
                NSFontAttributeName: font
            }];
    CGRect rect = [attributedText boundingRectWithSize:(CGSize){width, CGFLOAT_MAX}
                                               options:NSStringDrawingUsesLineFragmentOrigin
                                               context:nil];
    CGSize size = rect.size;
    

    Please note the documentation mentions:

    In iOS 7 and later, this method returns fractional sizes (in the size component of the returned CGRect); to use a returned size to size views, you must use raise its value to the nearest higher integer using the ceil function.

    So to pull out the calculated height or width to be used for sizing views, I would use:

    CGFloat height = ceilf(size.height);
    CGFloat width  = ceilf(size.width);
    

提交回复
热议问题