如何让UITextView在UITableViewCell中自动调整大小
-
05-07-2019 - |
题
设置:我在 UITableViewCell
的 contentView
中有一个 UITextView
。我希望它占据细胞的全部尺寸。我像这样创建文本视图:
UITextView *textView = [[[UITextView alloc] initWithFrame:CGRectMake(0,0,268,43)] autorelease];
textView.backgroundColor = [UIColor redColor];
textView.layer.cornerRadius = 10;
textView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
我覆盖heightForRowAtIndexPath以返回该行的200。
背景颜色正好让我知道它在哪里。在第一次查看时,单元格似乎正在自动调整大小。但是,我需要它在自动旋转界面时继续正确调整它的大小,这有时似乎只能工作,并且只有当我不编辑textView时。其他时候,它会调整视图的大小,使其高度非常小(看起来像-1),或者使其太宽,或者根本不调整大小。
我已尝试在单元格中覆盖layoutSubviews并且什么也不做,但即使这样也不会阻止视图在整个地方调整大小。
我现在已经对此进行了一段时间的攻击,但仍未找到解决办法。
解决方案
UITableViewCell具有固定的高度,UITableView的委托提供高度。旋转设备时,除非在tableView上调用 -reloadData
,否则行的高度永远不会改变。我将摆脱自动化并自己管理它。
初始化textField时,可以轻松地将框架设置为 CGRectZero
。然后实现 -layoutSubviews
(并在该方法中调用super,在设置子视图的帧之前)并根据 contentRect设置UITextField的框架代码>单元格的属性。
- (id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
if(self = [super ...]){ // or -initWithStyle:reuseIdentifier: whatever you want
_textView = [[UITextView alloc] initWithFrame:CGRectZero]; // Instance variable
// Probably not needed to set autoresizing mask
}
return self;
}
- (void)layoutSubviews {
[super layoutSubviews];
_textView.frame = CGRectMake(0.0f, 0.0f, self.contentRect.size.width, self.contentRect.size.height); // Adjust as needed
}
不隶属于 StackOverflow