2012-06-28 79 views
1

我有一个UITableView作为弹出式菜单,我想将其宽度设置为最宽的宽度UITableViewCell。但是,我试过获取单元格的宽度UILabel/contentView,并且它总是返回0.我尝试在添加到子视图之后以及表格重新加载并且结果相同之后执行此操作。我已经在tableView:cellForRowAtIndexPath:方法内完成了它,并且它在相同的结果之外。是否有可能做到这一点?我的代码列表如下:基于最长宽度的UITableViewCell调整UITableView的宽度

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *cellIdentifier = @"Cell"; 

    UITableViewCell *tableViewCell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 

    if (tableViewCell == nil) 
    { 
     tableViewCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease]; 
    } 

    [[tableViewCell textLabel] setFont:[UIFont fontWithName: @"Helvetica-Bold" size: 17]]; 
    [[tableViewCell textLabel] setText: [self.menuItems objectAtIndex:0]]; 
    [[tableViewCell imageView] setImage: [self.menuItems objectAtIndex:1]]; 

    if (tableViewCell.textLabel.frame.size.width > tableView.frame.size.width) 
    { 
     CGRect tableViewFrame = tableView.frame; 
     tableViewFrame.size.width = tableViewCell.textLabel.frame.size.width; 
     tableView.frame = tableViewFrame; 
    } 

    return tableViewCell; 
} 

更新:只是为了澄清,我没有兴趣在改变TableViewCell的宽度,而在TableView中重装。加载表格后,我会很好,然后计算出合适的最大宽度,然后用新的适当宽度重新加载它。

+0

出于某种原因,我不认为UITableViewCell的textLabel可以超出单元格的范围。单元格的内容视图将根据单元格的宽度缩放textLabel。我认为你也不能改变textLabel的框架。您应该尝试使用自己的标签子视图实现自定义单元格。 – Justin

+0

我不想拉伸UITableViewCell,我想找出最宽的UITableCell的宽度,然后相应地重新调整表格。 –

回答

1

解决这个问题的最好方法可能是从另一个角度。 textLabel将不会根据其包含的文本进行扩展。

您应该遍历self.menuItems数组并调用可应用于NSString的函数。

- (CGSize)sizeWithFont:(UIFont *)font; 

例如,

width = [menuItem sizeWithFont:font].width; 

保持数组中最大宽度的选项卡,并将您的tableview设置为该宽度。字体是你的单元格绘制标签的任何字体。

+0

感谢这是一个很好的解决方法,但仅仅是为了解决你最初的问题,我并没有试图扩展textLabel,只是想弄清楚最大标签的宽度,然后相应地重新调整tableView。 –

+0

textLabels将全部是相同的宽度,除非您在别处手动更改了它们。 – Tonester