如何在iOS 7中使用UITextView计算UITableViewCell的高度?
我在类似的问题上找到了很多答案,但sizeWithFont:参与了每个解决方案,这个方法已被弃用!
我知道我必须使用- (CGFloat)tableView:heightForRowAtIndexPath:但是如何计算TextView显示整个文本所需的高度?
我正在使用一个UITextView可以通过点击"更多"按钮进行扩展.问题如下:
在iOS6上我使用这个,
self.DescriptionTextView.text = @"loong string";
if(self.DescriptionTextView.contentSize.height>self.DescriptionTextView.frame.size.height) {
//set up the more button
}
Run Code Online (Sandbox Code Playgroud)
问题是在iOS7上contentSize.height返回的值不同于它在iOS6上返回的值(远远小于).为什么是这样?怎么解决?
我创建一个UITextView,向其添加文本,并将其放在视图中(带有容器)
UITextView *lyricView = [[UITextView alloc] initWithFrame:screen];
lyricView.text = [NSString stringWithFormat:@"\n\n%@\n\n\n\n\n\n", lyrics];
[container addSubview:lyricView];
[self.view addSubview:container];
Run Code Online (Sandbox Code Playgroud)
然后我获得它的大小以便与按钮一起使用并将其添加到UITextView
CGRect size = [lyrics boundingRectWithSize:CGSizeMake(lyricView.frame.size.width, MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:[lyricView font]}
context:nil];
UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[doneButton setFrame:CGRectMake(56, size.size.height + 55, 208, 44)];
[doneButton setTitle:@"Done" forState:UIControlStateNormal];
[lyricView addSubview:doneButton];
Run Code Online (Sandbox Code Playgroud)
这适用于大多数情况.这将遵循\n换行符(就像我在stringWithFormat中添加的那样),但它不会尊重由文本视图自动添加的自动换行.因此,如果lyrics有一个不适合屏幕的行,UITextView将包装它(正如它应该的那样),但size现在比它应该略短,因为它不尊重文本视图包装.
在iOS 6中,我使用此代码来获取以下行中的行数UITextView:
int numLines = textView.contentSize.height / textView.font.lineHeight;
Run Code Online (Sandbox Code Playgroud)
但这在iOS 7中不起作用.如何获得iOS 7中UITextView的总行数?
最近使用XCode 5将我的应用程序更新到iOS 7,发现boundingRectWithSize给出了不同的高度(在大小部分)计算属性字符串的边界.
以下行给出了iOS 6和iOS 7之间的不同结果:
CGRect rect = [self boundingRectWithSize:CGSizeMake(inWidth, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil];
Run Code Online (Sandbox Code Playgroud)
"self"是NSAttributedString,"inWidth"是字符串应该适合的最大宽度(以像素为单位).
我认为这是因为iOS 7具有与iOS 6不同的字体处理.
任何人都有一个工作的解决方案来计算两个iOS版本的字符串的高度?
这个问题已被问过几次,但我真的找不到答案......
在iOS6中,每当键盘出现时我都会使用以下内容来调整UITextView的大小.在iOS7下,行为不是应该的(在我的情况下,似乎没有任何东西正在调整大小).我怀疑原因是iOS7的自动布局/约束行为.有什么建议?("notePad"是我的UITextView)?
- (void)keyboardWasShown:(NSNotification*)aNotification
{
NSDictionary* info = [aNotification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
//NSLog(@"KeyboardSize: %f.%f", kbSize.width, kbSize.height);
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, (kbSize.width > kbSize.height ?
kbSize.height : kbSize.width), 0);
self.notePad.contentInset = contentInsets;
self.notePad.scrollIndicatorInsets = contentInsets;
}
Run Code Online (Sandbox Code Playgroud) ios7 ×5
objective-c ×4
ios ×3
cocoa-touch ×2
uitextview ×2
frame ×1
height ×1
ios6 ×1
uitableview ×1
xcode5 ×1