【发布时间】:2015-03-08 01:26:25
【问题描述】:
所以我在这里遇到了一些问题。我正在尝试将UITextView 作为UITableViewController 的footerView。
但是,由于根据 UITextView 拥有的数据(在viewDidLoad 中设置),它在运行时可能是不同的文本。所以我永远不知道UITextView 会有多高。它的宽度与 UITableView 相同。
我想如果我得到UITableView 的宽度和TextView 的文本,我可以计算出它应该是的大小。所以我为(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section:写了这段代码
//get the width of the tableView.
CGFloat width = self.tableView.frame.size.width;
//if it's bigger than the screen for some reason, or zero, set it to the screen's width.
if (width > [[UIScreen mainScreen] bounds].size.width || !width)
width = [[UIScreen mainScreen] bounds].size.width - 10;
//get the text from the textView, including attributes.
NSAttributedString *attributedText = _textView.attributedText;
//figure out the size it's supposed to be.
CGRect rect = [attributedText boundingRectWithSize:(CGSize){width, CGFLOAT_MAX}
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
CGSize size = rect.size;
size.height = ceilf(size.height);
size.width = ceilf(size.width);
//return the height, plus a little padding to be safe.
return size.height + 10;
所以这是丑陋的事情。在调用tableView:heightForFooterInSection: 时,TableView 的框架是一些古怪的数字,例如 600。计算错误,通常太小,UITextView 被返回的低高度切断。
但是,如果我旋转设备,这段代码会再次运行,它工作!所以我知道这段代码很好......如果稍后运行。
如果我在任何时候执行[tableView reloadData],它也会修复TableView。只有在第一次加载时它才会被切断。
如果我能想出一种方法来重新加载 tableView once 在它完成加载后,那会解决它,但我不知道该怎么做,这有点像无论如何,hack-y 解决方案。
谁能帮我找出更好的逻辑?我被难住了一段时间。
【问题讨论】:
-
您是否尝试在
-viewDidAppear:中调用此代码?或者干脆在-viewDidAppear:中调用[tableView reloadData]? -
我确实想到了这个!奇怪的是,它仍然有相同的结果。我必须旋转并旋转回去才能修复它。
-
如果
tableView的宽度等于屏幕的宽度;我会使用屏幕宽度作为参考,或者计算tableView相对于屏幕宽度的宽度作为百分比,以确保每次返回都相同。
标签: ios objective-c iphone uitableview uitextview