自动调整UITextView和UIScrollView

den*_*484 11 iphone uiscrollview uitextview autoresize

我已经在Stack Overflow和Google上进行了几次搜索,但是我找不到解决问题的方法.

我有一个产品的详细信息视图,其中包括UIScrollView和一些子视图(UIImageView,UILabel,UITextView).你可以在这里找到一个例子.

首先,我想将UITextView(不是文本本身!)自动调整到相应的高度.然后我想自动调整整个UIScrollView,使其符合我的UITextView及其上方元素的高度.我试过以下代码:

myUITextView.frame = CGRectMake(2.0, 98.0, 316.0, self.view.bounds.size.height);

[scrollView setContentOffset:CGPointMake(0.0, 0.0) animated:NO];
scrollView.contentSize = CGSizeMake(320.0, 98.0 + [myUITextView frame].size.height);

[self.view addSubview:scrollView];
Run Code Online (Sandbox Code Playgroud)

98.0 + [myUITextView frame] .size.height)因为我的想法是:在获得myUITextView的高度后,将其他子视图(98.0)的高度添加到它.

不幸的是它不能很好地工作.根据UIScrollView的内容,它太短或太长.我做了一些日志记录,结果是UITextView的高度始终相同:

2010-01-27 14:15:45.096 myApp [1362:207] [myUITextView frame] .size.height:367.000000

谢谢!

Ron*_*iew 22

实际上有一种非常简单的方法可以使用contentSize将UITextView调整到正确的高度.

CGRect frame = _textView.frame;
frame.size.height = _textView.contentSize.height;
_textView.frame = frame;
Run Code Online (Sandbox Code Playgroud)

需要注意的一点是,只有使用addSubview将UITextView添加到视图,才能使用正确的contentSize .在此之前,它等于frame.size


dea*_*rne 0

UITextView 不会自动根据其内容调整自身大小(据我所知无论如何),因此您需要自己获取文本的大小并相应地调整 UIView 的大小。

此页面上的函数会有所帮助 - 您可以使用它们来获取字符串的宽度和高度,例如

// Get the size that the string will render at
NSString *contents = @"This is the content of your UITextView";
CGSize areaSize = [contents sizeWithFont:myView.font forWidth:myView.frame.size.width lineBreakMode:UILineBreakModeWordWrap];

// Then set the frame of your UITextView to be the right size
myView.bounds = CGRectMake(0, 0, areaSize.width, areaSize.height);
Run Code Online (Sandbox Code Playgroud)

然后,您可以在其周围布局其他组件。

希望这可以帮助,

S

PS 警告,文档的链接是正确的,但我的代码示例未经测试,抱歉:)