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

查看:160
本文介绍了如何在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

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 mid - 线程可能很昂贵。我看到的替代方法是在布局回调上调整外部容器的大小(触发或不取决于操作系统是否需要布局),外部容器调整大小将导致另一个布局更新。两种更新都可以与其他布局更新结合使用,以提高效率。如果你有这样的解决方案并且你可以证明 更有效率,那就把它添加为答案,我一定会在这里提一下。

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天全站免登陆