2012-08-25 42 views
2

我嘗試下面的代碼,但輸出始終是0.000000:iOS - 如何計算UITableViewCell的默認textLabel的寬度?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    static NSString *CellIdentifier = @"CellNotification"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 
    cell.textLabel.text = @"Test Test Test. I am a cell."; 

    NSLog(@"%f", cell.textLabel.frame.size.width); 

    return cell; 
} 

我怎麼能知道什麼是默認的UITableViewCell是的寬度是多少?我需要這些信息,因爲我要設置的UITableViewCell高度在

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
+0

對於呼叫 ' - ( CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath' 你不需要你只需要返回高度的寬度。 –

+1

沒有太多的答案,但我會去「300」。它可能會在下一次iOS更新中崩潰,但其他應用程序也會崩潰:) – user1071136

+0

你能告訴我你是如何得到這個數字的嗎?謝謝! – iForests

回答

0

NSLog您使用上述在細胞內要求的爲textLabel的寬度,而不是實際的細胞。

NSLog(@"%f",cell.frame.size.width); 

此外,如果你不使用分組表樣式,單元格寬度應返回相同的表格的寬度。

編輯:我不確定這是否是問題,但如果你問如何設置你的細胞的寬度,你不必。這是爲你處理的。

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { 

    NSLog(@"%@",NSStringFromCGRect(cell.textLabel.frame)); 
} 

編輯2:

嘗試修改此:

if (cell == nil) 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 
    cell.textLabel.text = @"Test Test Test. I am a cell."; 

向該:

if (cell == nil){ 
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 
} 

cell.textLabel.text = @"Test Test Test. I am a cell."; 
+0

標籤的寬度與單元格的寬度不同,因爲有填充。爲什麼textLabel的寬度爲零? – iForests

+2

我不打算設置單元格的寬度。我只需要寬度,所以我可以做這樣的事情: - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {@「一個字符串」sizeWithFont:[UIFont fontWithName:@「HelveticaNeueLTStd-Lt 「size:16] constrainedToSize:CGSizeMake(標籤的寬度,20000.0f)lineBreakMode:UILineBreakModeTailTruncation] .height + 35; } – iForests

+0

由於填充,標籤的寬度與單元格的寬度不同。我必須知道標籤的寬度,而不是單元格。 – iForests

0

單元格的寬度將是表格的寬度,除非你的桌子是分組的,在這種情況下,它稍小一點。

但是,您可能希望使用任何標籤的寬度來顯示文本而不是單元格本身。

還有一個警告是,在創建任何單元格之前,表中的每一行都會調用heightForRow...方法,因此您可能必須改用已知值。

+1

由於填充,標籤的寬度與單元格的寬度不同。我必須知道標籤的寬度,而不是單元格。 – iForests

0

我想你應該在測試爲textLabel寬度: - (空)的tableView:(UITableView的*)的tableView willDisplayCell:(的UITableViewCell *)細胞forRowAtIndexPath:(NSIndexPath *)indexPath

+0

我相信這是您第一次能夠訪問UI元素。由此,文本標籤將被調整大小以適應其單元格。然而,這發生在heightForRow ...被調用之後。 –

相關問題