find out height of a UILabel which is size to fit

≡放荡痞女 提交于 2020-01-06 08:24:31

问题


I am trying to find out the height of the UILabel when the height of the UILabel changes dynamically that is when it is sizeToFit enabled. What is the way to figure out the height of the UILabel? Of course the value frame.size.height is obviously wrong when I enable sizeToFit.

Thanks.


回答1:


try this it may be help you..

-(CGSize)lblSize:(NSString *)content lblFont:(UIFont *)contectLblFont width:(int)Width
{
    CGSize maximumLabelSize;
    maximumLabelSize = CGSizeMake(Width,9999);
    NSAttributedString *attributedText =
    [[NSAttributedString alloc]
     initWithString:content
     attributes:@
     {
     NSFontAttributeName:contectLblFont
     }];
    CGRect rect = [attributedText boundingRectWithSize:(CGSize){maximumLabelSize.width, CGFLOAT_MAX}
                                               options:NSStringDrawingUsesLineFragmentOrigin
                                               context:nil];
    CGSize size = rect.size;
    return size;
}

and use inside table view delegate

CGSize expectedLabelSize=[self lblSize:[NSString stringWithFormat:@"%@",[[loadMoreArray objectAtIndex:indexPath.row]valueForKey:@"text"]] lblFont:cell.self.lbldetail.font width:310];

    cell.self.lbldetail.frame=CGRectMake(5,cell.imgProfile.frame.size.height+cell.imgProfile.frame.origin.y+2, 300,expectedLabelSize.height+10);



回答2:


I also using sizeToFit but getting Correct result try this may be helpfull. Plz try must.

 UILabel *detailsLabel = [[UILabel alloc]initWithFrame:CGRectMake(0,50,320,30)];
 detailsLabel.text = [textDic valueForKey:@"Text"];
 detailsLabel.textColor = [UIColor grayColor];
 detailsLabel.numberOfLines = 0;
 [detailsLabel sizeToFit];
 [scrollViewObj addSubview:detailsLabel];
 NSLog(@"Label Height %f",  detailsLabel.frame.size.height );

Every thing working fine in my current project .Thanks Cheers ..



来源:https://stackoverflow.com/questions/24278539/find-out-height-of-a-uilabel-which-is-size-to-fit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!