2012-07-31 109 views
0

我想調整我的UITextView中的文本的大小,使它適合。我有以下代碼:基於UITextView幀大小調整文本

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]]; 

然而,這裏就是我得到:

enter image description here

我試着用不同的換行模式,還可以設置自動調整大小爲無,但是事實並非如此幫幫我。任何想法?

回答

1

while循環不會做你想做的,因爲你正在使用 storyTitleSize.height 確定框架,不會顧及周圍的文字效果的包的大小。一個建議是截斷字符串,只顯示一定數量的標題字符。否則,你將需要計算你將有多少換行符有,基於幀和字符串的長度的寬度,並使用

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

希望有所幫助。

您也可以動態調整的幀(的UITextView)在本thread

+0

yea..the問題是我不希望調整框架..我想要調整的文本 – adit 2012-07-31 18:16:21

+0

如何計算換行符的數量? – adit 2012-07-31 18:18:40

+0

請參閱NSString UIKit Additions Reference(https://developer.apple.com/library/ios/#documentation/UIKit/Reference/NSString_UIKit_Additions/Reference/Reference.html),特別是'sizeWithFont:forWidth:lineBreakMode'方法。這應該會返回一個CGSize,它應該具有適當的字符串高度。我不在我的Mac上進行驗證,但它應該能夠滿足您的需求。也就是說,如果返回的高度大於靜態框架,請減少字體大小,然後重試。 – jwest 2012-07-31 18:39:27

0

嘗試這些代碼

while (self.textView.contentSize.height >= frameHeight){ 
    currentFontSize--; 
    currentFont = [UIFont fontWithName:kProximaNovaBold size:currentFontSize]; 
    [self.textView setFont:currentFont]; 
    self.textView.text = @"your string"; 
} 
+0

爲什麼這首先會有所幫助? – adit 2012-07-31 18:16:59

+0

我想。你有沒有嘗試過? constrainedToSize:(CGSize)size,size是字符串的最大可接受大小。 – 2012-07-31 18:20:59

+0

@adit Btw。你有沒有嘗試過UITextView的contentSize屬性? – 2012-07-31 18:24:44