我正在开发一个应用程序,我有一个UITableViewCell的自定义子类.我想根据里面的文字使单元格的高度动态化.我尝试在我的heightForRowAtIndexPath方法中做到这一点.但我有一些问题,以下代码导致和EXC_BAD_ACCESS(代码= 2地址= 0xb7ffffcc)错误.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
PostCell *cell = (PostCell *)[tableView cellForRowAtIndexPath:indexPath];
CGSize postTextSize;
if (![cell.postText.text isEqualToString:@""]) {
postTextSize = [cell.postText.text sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(cell.postText.frame.size.width, 200)];
} else {
postTextSize = CGSizeMake(cell.postText.frame.size.width, 40);
}
return postTextSize.height + cell.userName.frame.size.height + 10;
}
Run Code Online (Sandbox Code Playgroud)
如果我改为:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 100;
}
Run Code Online (Sandbox Code Playgroud)
有用.
它似乎在这条线上崩溃:PostCell *cell = (PostCell *)[tableView cellForRowAtIndexPath:indexPath];,我不知道为什么.我试图建立干净并重置模拟器,但都没有工作.任何想法为什么会这样?
如何以编程方式设置视图高度我已经尝试此代码
cell.viewMain.frame = CGRectMake(cell.viewMain.frame.origin.x, cell.viewMain.frame.origin.y, cell.viewMain.frame.size.width, 65.0)
Run Code Online (Sandbox Code Playgroud)
但这不起作用.
更新:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("updateCell", forIndexPath: indexPath) as! UpdateCell
if self.data[indexPath.row] == "b" {
tbUpdate.rowHeight = 85
cell.viewMain.frame = CGRectMake(cell.viewMain.frame.origin.x, cell.viewMain.frame.origin.y, cell.viewMain.frame.size.width, 65.0)
}else{
tbUpdate.rowHeight = 220
cell.viewMain.frame = CGRectMake(cell.viewMain.frame.origin.x, cell.viewMain.frame.origin.y, cell.viewMain.frame.size.width, 200.0)
}
return cell
}
Run Code Online (Sandbox Code Playgroud)