0

I have a UILabel and its text is generated dynamically, so depending upon text, UILabel width increases from iOS6 to iOS8. Is there any solution for this? it is only working on iOS7 and in iOS6.0 boundingRectWithSize method is crashing, its say boundingRectWithSize method only for iOS7.0 and above.

float widthIs =[[tagsArray objectAtIndex:i] boundingRectWithSize:_tagsValue.frame.size options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:_tagsValue.font } context:nil].size.width;
_tagsValue.frame=CGRectMake(prevTag, 2, widthIs+20, 30);
prevTag+=widthIs+30;
falcon143
  • 702
  • 4
  • 19

3 Answers3

1

Use this, this will work on IOS6 & IOS7. But I am not sure about IOS8 as i haven't test it on IOS8.

float width = [LABEL_TEXT_STRING sizeWithFont:LABEL_FONT constrainedToSize:DEFAULT_SIZE_OF_LABEL lineBreakMode:LABEL.lineBreakMode].width;
Surjeet Singh
  • 11,691
  • 2
  • 37
  • 54
1

you need to put a check for iOS6 and iOS7,

if([[[tagsArray objectAtIndex:i] respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)]){
    float widthIs =[[tagsArray objectAtIndex:i] boundingRectWithSize:_tagsValue.frame.size options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:_tagsValue.font } context:nil].size.width;
    _tagsValue.frame=CGRectMake(prevTag, 2, widthIs+20, 30);
    prevTag+=widthIs+30;
}
else{
    float widthIs = [[[tagsArray objectAtIndex:i] sizeWithFont:font constrainedToSize:(CGSize){CGFLOAT_MAX, CGFLOAT_MAX}];
}
Manish Agrawal
  • 10,958
  • 6
  • 44
  • 76
-1

Use this method to get the Width
Pass your label as param

 - (CGFloat)getWidth:(UILabel *)label{

      CGSize sizeOfText = [label.text boundingRectWithSize: CGSizeMake(CGFLOAT_MAX, self.bounds.size.height)
                                                  options: (NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                                               attributes: [NSDictionary dictionaryWithObject:label.font
                                                forKey:NSFontAttributeName]
                                                  context: nil].size;

    return sizeOfText.width; 

    }
Rajesh
  • 10,318
  • 16
  • 44
  • 64