2012-06-28 78 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