1

In my iPad app I am showing scrolling UILabel with text that will be fetched from the web service and the text size of the same need to be set Dynamic. My problem is that I will have to set the width of the UILabel according to the length of the text to be fetched from the web service.

I have tried all or most of the solutions possible but in vain.

Say if the NSString where I am storing the string fetched from the server is with 300 characters,it shows 2270 as width using the following code.

CGFloat width =  [ScrollingLabel.text sizeWithFont:ScrollingLabel.font].width;

ScrollingLabel.frame = CGRectMake(1024,720,width,45);

But then also I am not getting half of the string in the app.

halfer
  • 19,824
  • 17
  • 99
  • 186
Yama
  • 2,649
  • 3
  • 31
  • 63
  • Your code works fine here. Could it be that you resize the label elsewhere, e.g. with autoresizing masks? – omz May 18 '12 at 09:41

2 Answers2

2

I could get the solution of my problem just by multiplying the width with 2 that was been resulting with the code :

CGFloat width =  [ScrollingLabel.text sizeWithFont:ScrollingLabel.font].width;

ScrollingLabel.frame = CGRectMake(1024,720,width,45);
Yama
  • 2,649
  • 3
  • 31
  • 63
1

Actually the best way to accomplish this is to write a category of UILabel and add the method:

- (CGFloat)expectedWidth
{
    CGSize size = [self.text sizeWithFont:self.font
                        constrainedToSize:CGSizeMake(FLT_MAX,self.bounds.size.height)
                            lineBreakMode:self.lineBreakMode];

     return size.width;
}
apouche
  • 9,703
  • 6
  • 40
  • 45