iOS:UITextView自适应高度

来源:互联网 发布:网络理论 编辑:程序博客网 时间:2024/05/07 15:48

今天已知在使用根据内容长度和textview宽度计算出textview的height,但是总是会有各种各样的奇葩问题,最为突出的一个就是明明输满屏幕的一串字母,计算出来的宽度只有305px,这直接导致了当一行输满无法转到下一行。无奈之下转到stackoverflow中寻求答案。下面是来自stackoverflow的答案:

- (CGFloat)measureHeightOfUITextView:(UITextView *)textView{    if ([textView respondsToSelector:@selector(snapshotViewAfterScreenUpdates:)])    {        CGRect frame = textView.bounds;                // Take account of the padding added around the text.                UIEdgeInsets textContainerInsets = textView.textContainerInset;        UIEdgeInsets contentInsets = textView.contentInset;                CGFloat leftRightPadding = textContainerInsets.left + textContainerInsets.right + textView.textContainer.lineFragmentPadding * 2 + contentInsets.left + contentInsets.right;        CGFloat topBottomPadding = textContainerInsets.top + textContainerInsets.bottom + contentInsets.top + contentInsets.bottom;                frame.size.width -= leftRightPadding;        frame.size.height -= topBottomPadding;                NSString *textToMeasure = textView.text;        if ([textToMeasure hasSuffix:@"\n"])        {            textToMeasure = [NSString stringWithFormat:@"%@-", textView.text];        }                // NSString class method: boundingRectWithSize:options:attributes:context is        // available only on ios7.0 sdk.                NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];        [paragraphStyle setLineBreakMode:NSLineBreakByWordWrapping];                NSDictionary *attributes = @{ NSFontAttributeName: textView.font, NSParagraphStyleAttributeName : paragraphStyle };                CGRect size = [textToMeasure boundingRectWithSize:CGSizeMake(CGRectGetWidth(frame), MAXFLOAT)                                                  options:NSStringDrawingUsesLineFragmentOrigin                                               attributes:attributes                                                  context:nil];                CGFloat measuredHeight = ceilf(CGRectGetHeight(size) + topBottomPadding);        return measuredHeight;    }    else    {        return textView.contentSize.height;    }}

只想说stackoverflow真的很强大

原问题地址

0 0
原创粉丝点击