2011-04-15 44 views
0

我想捕獲一個實例變量中的UILabel的高度。我正在使用默認樣式UITableViewCellStyleValue2何時捕捉UILabel的高度?

截至目前,我試圖捕捉高度

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 

的代碼創建單元格時(跳過簡潔的deque'd東西):

UITableViewCell *testCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:@"myCell"] autorelease]; 

testCell.detailTextLabel.lineBreakMode = UILineBreakModeWordWrap; 
testCell.detailTextLabel.numberOfLines = 10; 

testCell.selectionStyle = UITableViewCellSelectionStyleNone; 

testCell.textLabel.text = @"LabelName"; 
testCell.detailTextLabel.text = [object valueForKey:@"key"]; 
[testCell.detailTextLabel sizeToFit]; //still says 0.00 :-(

labelHeight = testCell.detailTextLabel.bounds.size.height; 
NSLog(@"testCell height is %f", testCell.detailTextLabel.bounds.size.height); // equals 0.00 
NSLog(@"cellFrame is %f", testCell.frame); //also says 0.00 
return cell; 

NSLog狀態高度是0.00。

那麼,哪裏是捕捉標籤高度的好地方?或者,我錯過了什麼?當我將它分配給[someObject valueForKey:theKey]時,我會認爲detailTextLabel的界限會被設置。謝謝!

編輯:完整的代碼。

回答

1

請將所有代碼發佈到cellForRowAtIndexPath中。 我懷疑你沒有給detailTextLabel一個非零的框架(或邊界)。 你也可以NSLog cell.frame看看它的寬度和高度是多少。

+0

請參閱編輯的代碼。謝謝! – 2011-04-15 19:09:29

+0

你永遠不會分配一個框架的detailTextLabel,所以它默認爲零。你需要像這樣testCell.frame = CGRectMake(0,0,100,30);然後[testCell addSubview:detailTextLabel];或者添加detailTextLabel作爲子視圖,然後調整大小以適合。最後,NSLog(@「cell frame:%f,%f%f,%f」,cell.frame.origin.x,cell.frame.origin.y,cell.frame.size.width,cell.frame.size 。高度);會告訴你關於細胞框架的事實。 – Rayfleck 2011-04-15 19:16:59

+0

邁克,謝謝你的幫助! – 2011-04-15 20:49:47

0

在分配labelHeight之前,您是否嘗試過撥打[cell.detailTextLabel sizeToFit]?我的理解是,標籤的大小應該在這一點上,並且您應該得到非零值(假設文本不爲空)。

+0

感謝您的建議,但NSLog仍然顯示高度爲0.00。 – 2011-04-15 19:08:56