UITextView 自适应高度,搬来一篇stack上的:
 
Is there a good way to adjust the size of a UITextView to conform to its content? Say for instance I have a UITextView that contains one line of text:

"Hello world"

I then add another line of text:

"Goodbye world"

Is there a good way in Cocoa Touch to get the rect that will hold all of the lines in the text view so that I can adjust the parent view accordingly?

As another example, look at the Notes field for events in the Calendar application--note how the cell (and the UITextView it contains) expands to hold all lines of text in the notes string.

In my (limited) experience,

  - (CGSize)sizeWithFont:(UIFont *)font forWidth:(CGFloat)width lineBreakMode:(UILineBreakMode)lineBreakMode 

does not respect newline characters, so you can end up with a lot shorter CGSize than is actually required.
  - (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size 

does seem to respect the newlines.

Also, the text isn't actually rendered at the top of the UITextView. In my code, I set the new height of the UITextView to be 24 pixels larger than the height returned by the sizeOfFont methods.

This works for both iOS 6.1 and iOS 7:

 - (void)textViewDidChange:(UITextView *)textView
{
CGFloat fixedWidth = textView.frame.size.width;
CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];
CGRect newFrame = textView.frame;
newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);
textView.frame = newFrame;
}
Or in Swift
     let fixedWidth = textView.frame.size.width
textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max))
let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max))
var newFrame = textView.frame
newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
textView.frame = newFrame;

If you want support for iOS 6.1 then you should also:
  textview.scrollEnabled = NO;  

There is actually a very easy way to do resizing of the UITextView to its correct height of the content. It can be done using the UITextView contentSize.

  CGRect frame = _textView.frame;
frame.size.height = _textView.contentSize.height;
_textView.frame = frame;  One thing to note is that the correct contentSize is only available after the UITextView has been added to the view with addSubview. Prior to that it is equal to frame.size

This will not work if auto layout is ON. With auto layout, the general approach is to use the sizeThatFits method and update the constant value on a height constraint.

  CGSize sizeThatShouldFitTheContent = [_textView sizeThatFits:_textView.frame.size]; 

 heightConstraint.constant = sizeThatShouldFitTheContent.height; 

heightConstraint is a layout constraint that you typically setup via a IBOutlet by linking the property to the height constraint created in a storyboard.


Just to add to this amazing answer, 2014, if you:

  [self.textView sizeToFit]; 

there is a difference in behaviour with the iPhone6+ only:

With the 6+ only (not the 5s or 6) it does add "one more blank line" to the UITextView. The "RL solution" fixes this perfectly:

  CGRect _f = self.mainPostText.frame;
_f.size.height = self.mainPostText.contentSize.height;
self.mainPostText.frame = _f; 

It fixes the "extra line" problem on 6+.

 

In my (limited) experience,

  - (CGSize)sizeWithFont:(UIFont *)font forWidth:(CGFloat)width lineBreakMode:(UILineBreakMode)lineBreakMode 

does not respect newline characters, so you can end up with a lot shorter CGSize than is actually required.
  - (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size 

does seem to respect the newlines.

Also, the text isn't actually rendered at the top of the UITextView. In my code, I set the new height of the UITextView to be 24 pixels larger than the height returned by the sizeOfFont methods.

In iOS6, you can check the contentSize property of UITextView right after you set the text. In iOS7, this will no longer work. If you want to restore this behavior for iOS7, place the following code in a subclass of UITextView.

 - (void)setText:(NSString *)text
{
[super setText:text]; if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_6_1) {
CGRect rect = [self.textContainer.layoutManager usedRectForTextContainer:self.textContainer];
UIEdgeInsets inset = self.textContainerInset;
self.contentSize = UIEdgeInsetsInsetRect(rect, inset).size;
}
}
 

To make a dynamically sizing UITextView inside a UITableViewCell, I found the following combination works in Xcode 6 with the iOS 8 SDK:

  • In Storyboard/IB, add a UITextView to a UITableViewCell and constrain it to the sides
  • In Storyboard/IB, uncheck Scrolling Enabled (with scrolling enabled, the frame of the UITextView is independent of the content size, but with scrolling disabled, there is a relationship between the two)
  • In viewDidLoad, tell the tableView to automatically calculate row heights:

      tableView.estimatedRowHeight = ; 
  •  tableView.rowHeight = UITableViewAutomaticDimension; 

For read-only dynamically sizing UITextViews, that’s it. If you’re allowing users to edit the text in your UITextView, you also need to:

  • Implement the textViewDidChange: method of the UITextViewDelegate protocol, and tell the tableView to repaint itself every time the text is edited:

     - (void)textViewDidChange:(UITextView *)textView;
    {
    [tableView beginUpdates];
    [tableView endUpdates];
    }
  • And don’t forget to set the UITextView delegate somewhere, either in Storyboard/IB or in tableView:cellForRowAtIndexPath:

How do I size a UITextView to its content?的更多相关文章

  1. Confluence 6 用户宏示例 - Color and Size

    这个示例定义了如何向你宏中传递参数.我们将会创建一个字体样式宏,在这个宏中有 2 个参数,允许用户在这 2 个参数中指定宏中包含的字体的颜色大小. Macro name stylish Visibil ...

  2. IOS开发基础知识--碎片22

    1:设置有间距的表格行(UITableViewStyleGrouped) .设置section的数目,即是你有多少个cell - (NSInteger)numberOfSectionsInTableV ...

  3. 何为分类,UIImageView举例

    终于开始自己这个“聚水成洋”的路程了. 经过近一年的iOS学习和开发,遇到很多困难,一开始的陌生和畏惧,中途的困惑和纠结,解决问题后的豁然开朗和总结提升,自己就在这样一个不断的循环中逐渐成长起来了. ...

  4. 深入理解Auto Layout 第一弹

    本文转载至 http://zhangbuhuai.com/2015/07/16/beginning-auto-layout-part-1/ By 张不坏 2015-07-16 更新日期:2015-07 ...

  5. 使用uilabel重新自调整高度后显示横线和竖线问题

    这个使用uilabel自调节高度发现的问题,代码如下: //content label                        NSString *contentValue = ((Messag ...

  6. JQuery 滚动条插件perfect-scrollbar

    原文地址 https://github.com/noraesae/perfect-scrollbar perfect-scrollbar Tiny but perfect jQuery scrollb ...

  7. 如何生成每秒百万级别的 HTTP 请求?

    第一篇:<如何生成每秒百万级别的 HTTP 请求?> 第二篇:<为最佳性能调优 Nginx> 第三篇:<用 LVS 搭建一个负载均衡集群> 本文是构建能够每秒处理 ...

  8. common.js js中常用方法

    //创建CSS样式段 //classid: CSS样式段ID//font: 字体//size: 字体大小//color: 字体颜色//style: 字体风格function FCMakeCSSClas ...

  9. Quick-lua3.3之listview

    前言 listview列表,在游戏中非常常见,比如道具列表,玩家列表,排行榜等等.每个版本可能使用方法可能有些差别,但是大同小异,原理和用途都是那几种,设置方向,间隔等. 这里是quick-lua3. ...

随机推荐

  1. SQLPLUS使用

    1.CMD命令 2.输入SQLPLUS 3.如果oracle服务器中装有多个数据库实例,则在用户名处输入:用户名/密码@数据库名称.如果数据库服务器不在本机上,还需要加上数据库服务器的地址:用户名/密 ...

  2. C# yield return 用法与解析

    原文:C# yield return 用法与解析 C# yield return 用法与解析 本文参考自:http://www.jb51.net/article/54810.htm 当初没有认真理解 ...

  3. GNU工具链学习笔记

    GNU工具链学习笔记 1..so为动态链接库,.a为静态连接库.他们在Linux下按照ELF格式存储.ELF有四种文件类型.可重定位文件(Relocatable file,*.o,*.a),包含代码和 ...

  4. Integer Intervals(贪心)

    Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 12123   Accepted: 5129 Description An i ...

  5. (转载)php flush()刷新不能输出缓冲的原因分析

    (转载)http://www.webkaka.com/tutorial/php/2012/110628/ 在php程序编写中,flush()的使用率还是挺高的,它在网页表现即时信息效果时发挥了极为重要 ...

  6. 函数调用和给对象发消息(Runtime理解)

    在写代码的时候这个差距其实是不打看的出得,很多时候也就无所谓叫什么,很多人为了便于理解,干脆就叫函数调用.这个其实应该是oc的一个特色,消息发送.具体的类typedef struct objc_cla ...

  7. jquery常用见的正则表达式

    quickexpr = /^(?:[^<]*(<[ww]+>)[^>]*$|#([w-]+)$)/  (?:…)表示是一个非捕获型 [^<]表示是以"<& ...

  8. VB.NET版机房收费系统—DataGridView应用

    事实上,先前刚刚開始敲机房的时候,刚用到DataGridView的时候,总显得力不从心,先要一下子就学会,看了非常多的资料,但是依照写的时候,自己有不知道从什么地方下手,于是,当自己用查询SQL语句, ...

  9. NDN路由--OSPFN安装与配置

    现在的IP网络的问题已经暴露的很多了,各种改进的网络架构与设想非常多,但其中以基于内容为中心的网络发展最为迅速,其中,NDN的架构最为完整,代码也比较成熟.OSPFN是基于CCNX的,所以之前要安装C ...

  10. 1小时学Python脚本

    如果我们有这么一项任务:简单測试局域网中的电脑是否连通.这些电脑的ip范围从192.168.0.101到192.168.0.200.        思路:用shell编程.(Linux一般是bash而 ...