簡體   English   中英

自動調整UITextView和UIScrollView

[英]Autoresize UITextView and UIScrollView

我已經在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];

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

謝謝!

實際上有一種非常簡單的方法可以使用contentSize將UITextView調整到正確的高度。

CGRect frame = _textView.frame;
frame.size.height = _textView.contentSize.height;
_textView.frame = frame;

需要注意的一點是,只有使用addSubview將UITextView添加到視圖 ,才能使用正確的contentSize。 在此之前,它等於frame.size

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);

然后,您可以布局其周圍的其他組件。

希望這可以幫助,

小號

PS警告,文檔的鏈接是正確的,但我的代碼示例未經測試,抱歉:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM