Change the height of UILabel dynamically based on content

前端 未结 4 997
自闭症患者
自闭症患者 2020-12-06 08:49

I have a UILabel as subview of UIButton and I am passing the value from another view and populating in UILabel. Now, I want that

4条回答
  •  悲哀的现实
    2020-12-06 09:26

    This is the very simplest function for getting dynamic height for labels. You can just use this function.
    Here ceil is the predefind function for returns the smallest integer value. And MAXHEIGHT is maximum height for uilabel for example you can give 1000 also for future caluclations...

    -(CGFloat) getHeightForLabels : (UILabel *) label
        {
    
            CGSize widthMaxHeight = CGSizeMake(label.frame.size.width, MAXHEIGHT);
            CGSize size;
    
            NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
            CGSize boundingRect = [label.text boundingRectWithSize:widthMaxHeight
                                                          options:NSStringDrawingUsesLineFragmentOrigin
                                                       attributes:@{NSFontAttributeName:label.font}
                                                          context:context].size;
    
            size = CGSizeMake(ceil(boundingRect.width), ceil(boundingRect.height));
    
            return size.height;
        }
    

提交回复
热议问题