0

I am trying to adjust the size of the text in my UITextView so it fits. I have the following code:

NSString *storyTitle = [newsfeedToSubject.properties valueForKey:@"title"];

    int currentFontSize = 18;
    UIFont *currentFont = [UIFont fontWithName:kProximaNovaBold size:currentFontSize];
    CGSize storyTitleSize = [storyTitle sizeWithFont:currentFont constrainedToSize:self.newsfeedStoryTitle_.frameSize lineBreakMode:UILineBreakModeWordWrap];

    while (storyTitleSize.height >= self.newsfeedStoryTitle_.frameHeight){
        currentFontSize--;
        currentFont = [UIFont fontWithName:kProximaNovaBold size:currentFontSize];
        storyTitleSize = [storyTitle sizeWithFont:currentFont constrainedToSize:self.newsfeedStoryTitle_.frameSize lineBreakMode:UILineBreakModeWordWrap];
    }

    [self.newsfeedStoryTitle_ setFont:currentFont];
    [self.newsfeedStoryTitle_ setText:storyTitle];
    [self.newsfeedStoryTitle_ setBackgroundColor:[UIColor redColor]];

However, here's what I am getting:

enter image description here

I tried with different line break mode and also set the autoresize to none, but it didn't help. Any idea?

adit
  • 32,574
  • 72
  • 229
  • 373

2 Answers2

1

Your while loop will not do what you want because you are using storyTitleSize.height to determine the size of the frame, which will not take into account the wrap around effect of the text. One suggestion would be to truncate the string and only display a certain amount of characters of the title. Otherwise, you will need to calculate how many line breaks you will have, based on the width of the frame and the length of the string, and use

while(storyTitleSize.height * numLineBreaks >= self.newsFeedStoryTitle_.frameHeight)
{
    ...
}

Hope that helps.

You can also dynamically resize your frame (UITextView) as in this thread

Community
  • 1
  • 1
jwest
  • 100
  • 1
  • 1
  • 9
  • yea..the issue is I don't want to resize the frame.. I want the text to resize – adit Jul 31 '12 at 18:16
  • how do I calculate the number of line breaks? – adit Jul 31 '12 at 18:18
  • See the NSString UIKit Additions Reference (https://developer.apple.com/library/ios/#documentation/UIKit/Reference/NSString_UIKit_Additions/Reference/Reference.html), specifically the `sizeWithFont:forWidth:lineBreakMode` method. That should return you a CGSize that should have the appropriate height for the string. I am not at my Mac to verify, but it should do what you need. That is, if the height returned is larger than your static frame, decrease the font size like you were and try again. – jwest Jul 31 '12 at 18:39
0

try these code

while (self.textView.contentSize.height >= frameHeight){
    currentFontSize--;
    currentFont = [UIFont fontWithName:kProximaNovaBold size:currentFontSize];
    [self.textView setFont:currentFont];
    self.textView.text = @"your string";
}
lu yuan
  • 7,207
  • 9
  • 44
  • 78