1

我有一个UITableView用作弹出菜单的菜单,我想将其宽度设置为其最宽的宽度UITableViewCell。但是,我尝试获取单元格UILabel/的宽度,contentView但它始终返回 0。我尝试在添加到子视图和重新加载表格后执行此操作,结果仍然相同。我已经在tableView:cellForRowAtIndexPath:方法内部和外部完成了它,结果相同。是否有可能做到这一点?我的代码如下:

- (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;
}

更新:澄清一下,我对在重新加载 TableView 时更改 TableViewCell 的宽度不感兴趣。我可以加载表格,然后计算适当的最大宽度,然后用新的适当宽度重新加载它。

4

1 回答 1

1

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

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

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

例如

width = [menuItem sizeWithFont:font].width;

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

于 2012-06-28T17:30:38.847 回答