基于UITextView帧大小调整文本
我想调整我的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]];
然而,这里就是我得到:
我试着用不同的换行模式,还可以设置自动调整大小为无,但是事实并非如此帮帮我。任何想法?
while循环不会做你想做的,因为你正在使用 storyTitleSize.height
确定框架,不会顾及周围的文字效果的包的大小。一个建议是截断字符串,只显示一定数量的标题字符。否则,你将需要计算你将有多少换行符有,基于帧和字符串的长度的宽度,并使用
while(storyTitleSize.height * numLineBreaks >= self.newsFeedStoryTitle_.frameHeight)
{
...
}
希望有所帮助。
您也可以动态调整的帧(的UITextView)在本thread
尝试这些代码
while (self.textView.contentSize.height >= frameHeight){
currentFontSize--;
currentFont = [UIFont fontWithName:kProximaNovaBold size:currentFontSize];
[self.textView setFont:currentFont];
self.textView.text = @"your string";
}
为什么这首先会有所帮助? – adit 2012-07-31 18:16:59
我想。你有没有尝试过? constrainedToSize:(CGSize)size,size是字符串的最大可接受大小。 – 2012-07-31 18:20:59
@adit Btw。你有没有尝试过UITextView的contentSize属性? – 2012-07-31 18:24:44
yea..the问题是我不希望调整框架..我想要调整的文本 – adit 2012-07-31 18:16:21
如何计算换行符的数量? – adit 2012-07-31 18:18:40
请参阅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