0

I'm loading text data from xml to my today widget label so height can't be static. Since font size is 17px I counted that there are max 30 characters in one line, and by that I tried to set height like this

int number_of_characters = [self.string length];
[label sizeToFit];
self.preferredContentSize = CGSizeMake(self.view.frame.size.width, (number_of_characters/30)*22+40);

I add +40 to height because I have static text on top of widget, and multiple by 22 since font size is 17px I assumed that there's 5px spaceing between two lines.

But this doesn't work, I can't figure why :( . Is there some other way to make widget height dynamic?

user76541
  • 3
  • 1

1 Answers1

0

Try this code: You send him the 'stirng', 'width' and the font.

- (CGFloat)heightForValue:(NSString *)value andWidth:(CGFloat)width andFont:(UIFont *)font{

    NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                          font, NSFontAttributeName,
                                          nil];

    CGRect frame = [value boundingRectWithSize:CGSizeMake(width, 999.0f)
                                       options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading)
                                    attributes:attributesDictionary
                                       context:nil];
    //    CGSize size = [value sizeWithFont:font constrainedToSize:CGSizeMake(width, 99999.0f) lineBreakMode:NSLineBreakByWordWrapping];
    CGFloat result = frame.size.height;
    return result;
}

Example:

CGFloat height = [self heightForValue:@"This is example code." andWidth:250];
Altimir Antonov
  • 4,966
  • 4
  • 24
  • 26
  • Doesn't matter. It shouls be in the implementation. – Altimir Antonov Jan 24 '15 at 19:08
  • Ok, but I still don't get how I set preferredContentSize – user76541 Jan 24 '15 at 19:44
  • Copy my method in your .m file and change your function (number_of_characters/30)*22+40 with [self heightForValue:self.string andWidth:self.view.frame.size.width] – Altimir Antonov Jan 24 '15 at 19:50
  • After changing as you said I'm getting this error "Property 'string' not found on object of type' TodayViewController' " Pointing at this -> [self heightForValue:self. **string** andWidth:self.view.frame.size.width] – user76541 Jan 24 '15 at 20:02
  • No visible @interface for 'TodayViewController' declares the selector 'heightForValue:andWidth:' **and I put your code in** implementation TodayViewController – user76541 Jan 24 '15 at 20:22
  • Tnx for your help, but I got it working with my code by setting line spacing. – user76541 Jan 25 '15 at 01:29