NSString boundingRectWithSize slightly underestimating the correct height - why?

前端 未结 4 1049
时光说笑
时光说笑 2020-12-16 14:49

I\'m attempting to resize a text field / view automatically depending on its current width. In other words I want the width to stay constant but resize the height according

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-16 15:37

    I had the same Problem. I found the following in the Documentation:

    To correctly draw and size multi-line text, pass NSStringDrawingUsesLineFragmentOrigin in the options parameter.

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

    So this solved it for me:

    CGRect rect = [myLabel.text boundingRectWithSize:CGSizeMake(myLabel.frame.size.width, CGFLOAT_MAX)
                                                                options:NSStringDrawingUsesLineFragmentOrigin
                                                                attributes:@{NSFontAttributeName: myLabel.font}
                                                                context:nil];
    rect.size.width = ceil(rect.size.width);
    rect.size.height = ceil(rect.size.height);
    

    Update (Swift 5.1)

    An alternative Swift way to do this would be:

    let size = myLabel.text!.size(
        withAttributes: [.font: myLabel.font!]
    )
    let rect = CGSize(
      width: ceil(size.width),
      height: ceil(size.height)
    )
    

    See this answer for an Objective-C example.

提交回复
热议问题