2013-10-12 54 views
0

我嘗試在UITableViewCell的默認textLabel下添加一個輔助(自定義)標籤。如何在iOS中的UITableViewCell中獲取默認textLabel的大小?

我想正確設置框架,它應該真正在textLabel下面。但是,所有值都返回0,因此我無法正確準備自定義視圖的框架。

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

NSLog(@"%f, %f, %f, %f", cell.textLabel.frame.origin.x,cell.textLabel.frame.origin.y,cell.textLabel.frame.size.height,cell.textLabel.frame.size.width);

打印

0.000000, 0.000000, 0.000000, 0.000000

我怎樣才能爲我定製的二次模擬圖正確的X和Y

? (我知道的UITableViewCell具有類似這樣的一個模板,但我不希望使用詳細信息視圖模板)

+1

添加默認cell.textlabel –

回答

0

默認大小爲[細胞labelsize = 15 0 43.5 270]

你不會當cell = nil時獲取textLabel的大小。將你的桌面向上拖動&然後檢查日誌。你會發現這些值。

但是,如果你想要兩個標籤,然後使用此代碼。這很簡單。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
    { 
     UITableViewCell *cell =[ tableView dequeueReusableCellWithIdentifier:@"cell"]; 
     UILabel * invoiceTitle; 
     UILabel * projectTitle; 

     if(cell==nil) 
     { 
      cell=[[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"]autorelease]; 

      invoiceTitle  = [[UILabel alloc]initWithFrame:CGRectMake(14, 0, cell.contentView.frame.size.width, cell.contentView.frame.size.height/2)]; 
      [invoiceTitle setTag:111]; 
      [cell.contentView addSubview:invoiceTitle]; 
      [invoiceTitle release]; 

      projectTitle  = [[UILabel alloc]initWithFrame:CGRectMake(14, cell.contentView.frame.size.height/2 + 1, cell.contentView.frame.size.width - cell.contentView.frame.size.height/2]; 
      [projectTitle setTag:222]; 
      [cell.contentView addSubview:projectTitle]; 
      [projectTitle release]; 
     } 
     else 
     { 

      invoiceTitle = (UILabel *)[cell.contentView viewWithTag:111]; 
      projectTitle = (UILabel *)[cell.contentView viewWithTag:222]; 
     } 

     [projectTitle setText:LOCAL(@"Title1")]; 
     [invoiceTitle setText:@"Title2"]; 

     return cell; 
    } 

快樂編碼...

+0

我嘗試分配和設置「單元格」後能得到爲textLabel的大小的兩個自定義標籤就位。它不給大小。所以你的意思是我必須完全放棄使用默認的textLabel和「也」用自定義主標籤取代它。對? – frankish

+1

的確,我曾在很多項目中做過。這是做定製事情的好方法。因爲使用默認的textLabel有時會讓你的事情變得更糟。就像把一個標籤貼在另一個標籤上等等。如果它對你有幫助,請接受答案。 –

+0

默認UITableViewCell的textLabel的默認大小是正確的,但僅適用於iOS 7。在iOS 6中,textLabel的寬度爲280,origin.x爲15.您需要爲iOS 7及更早版本編碼時採取預防措施。 –

1

您可能很可能不會加載後立即獲得細胞的大小。最初cellForRowAtIndexPath:會給你零值。您必須以某種方式滾動出視圖或撥打[tableView reload]方法。這將使用新的值再次調用cellForRowAtIndexPath:。框架的起源將是不同的,但大小應該是相同的。我使用這種技術來獲取detailTextLabel.frame的大小。這是我的榜樣,我得到了大小:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    ...... 
    NSLog(@「detailCell frame is %@」, NSStringFromCGRect(cell.detailTextLabel.frame)); 
    ...... 
} 

好運

相關問題