如何在 iOS 7 上根据其内容调整 UITextView 的大小? [英] How do I size a UITextView to its content on iOS 7?

查看:24
本文介绍了如何在 iOS 7 上根据其内容调整 UITextView 的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用接受的答案此处 多年.

I've been using the accepted answer here for years.

在 iOS 7 上,contentSize.height 变为 frame.height-8,与文本内容无关.

On iOS 7, the contentSize.height becomes the frame.height-8, regardless of text content.

在 iOS 7 上调整高度的工作方法是什么?

What's a working method to adjust the height on iOS 7?

推荐答案

我喜欢这种最小的代码更改:只需在 addSubview 之后和抓取 height 之前添加这两行frame

I favor this minimal code change: Just add these two lines after addSubview and before grabbing the height of the frame

...
[scrollView1 addSubview: myTextView];

    [myTextView sizeToFit]; //added
    [myTextView layoutIfNeeded]; //added

CGRect frame = myTextView.frame;
...

这经过测试与 iOS 6 向后兼容.注意它收缩包装宽度.如果你只是对高度感兴趣并且有一个固定的宽度,只需获取新的高度但设置原始宽度,它在 iOS 6 和 7 上都像以前一样工作.

This is tested backwards compatible with iOS 6. NOTE that it shrink-wraps the width. If you're just interested in the height and have a fixed width, just grab the new height but set the original width, and it works just as before on both iOS 6 and 7.

(推测:它的大小也适合 iOS 7,但布局稍后更新或在单独的线程中更新,这会立即强制布局,以便及时更新其框架以使用其在同一线程中几行之后的高度值.)

注意:

1) 您可能会也可能不会以这种方式调整外部容器的大小.不过,它似乎确实是一个常见的片段,而且我已经在我的项目中使用了它.

1) You might or might not have implemented the outer container resize this way. It does seem to be a common snippet, though, and I've used it in my projects.

2) 由于 sizeToFit 似乎在 iOS 7 上按预期工作,您可能不需要过早的 addSubView.它是否仍然可以在 iOS 6 上运行我未经测试.

2) Since sizeToFit seems to work as expected on iOS 7, you likely don't need the premature addSubView. Whether it will still work on iOS 6 then is untested by me.

3) 推测:额外的 layoutIfNeeded 中间线程可能代价高昂.我所看到的另一种方法是在布局回调中调整外部容器的大小(是否触发取决于操作系统是否决定是否需要布局),其中外部容器调整大小将导致另一个布局更新.这两个更新可能会与其他布局更新相结合以提高效率.如果您确实有这样的解决方案,并且可以证明它更有效,请将其添加为答案,我一定会在此处提及.

3) Speculation: The extra layoutIfNeeded mid-thread might be costly. The alternative as I see it is to resize the outer container on the layout callback (fired or not depending on if the OS decides whether layout is needed or not) where the outer container resize will cause another layout update. Both updates might be combined with other layout updates to be more efficient. If you do have such a solution and you can show that it is more efficient, add it as answer and I'll be sure to mention it here.

这篇关于如何在 iOS 7 上根据其内容调整 UITextView 的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆