好的,根据我的研究和其他答案,问题是UITextView
' 的内容高度而不是滚动到特定偏移量。这是一个适用于 iOS 7 的解决方案:
首先,您需要重新创建UITextView
这样的:
NSString *reqSysVer = @"7.0";
NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
BOOL osVersionSupported = ([currSysVer compare:reqSysVer options:NSNumericSearch] != NSOrderedAscending);
if (osVersionSupported) {
NSLog(@"reset chatoutput");
CGRect outputFrame = self.chatOutput.frame;
[chatOutput removeFromSuperview];
[chatOutput release];
chatOutput = nil;
NSTextStorage* textStorage = [[NSTextStorage alloc] init];
NSLayoutManager* layoutManager = [NSLayoutManager new];
[textStorage addLayoutManager:layoutManager];
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:self.view.bounds.size];
[layoutManager addTextContainer:textContainer];
chatOutput = [[UITextView alloc] initWithFrame: outputFrame
textContainer: textContainer];
// if using ARC, remove these 3 lines
[textContainer release];
[layoutManager release];
[textStorage release];
[self.view addSubview: chatOutput];
}
然后,使用此方法获取UITextView
内容高度:
- (CGFloat)textViewHeightForAttributedText:(NSAttributedString*)text andWidth:(CGFloat)width
{
UITextView *calculationView = [[UITextView alloc] init];
[calculationView setAttributedText:text];
CGSize size = [calculationView sizeThatFits:CGSizeMake(width, FLT_MAX)];
NSLog(@"size: %f", size.height) ;
return size.height;
}
现在您可以设置内容偏移量:
CGPoint bottomOffset;
bottomOffset = CGPointMake(0, [self textViewHeightForAttributedText: self.chatOutput.attributedText andWidth: self.chatOutput.frame.size.width] - self.chatOutput.frame.size.height);
[self.chatOutput setContentOffset:bottomOffset animated:YES];
更新
我在 Apple 文档中读到NSAttributedString
:“NSAttributedString 对象的默认字体是 Helvetica 12-point,它可能与平台的默认系统字体不同。”
总之,如果您使用不同大小的不同字体,您也必须将它们设置为NSAttributeString
实例。否则,返回的高度将不符合您的期望。你可能想使用这样的东西:
NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObject: [UIFont systemFontOfSize: 18.0] //or any other font or size
forKey: NSFontAttributeName];
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString: currentPost.postMessageText attributes: attrsDictionary];
frame.size.height = [self textViewHeightForAttributedText: attributedString andWidth: 280.0];
[attributedString release];