2014-03-03 54 views
0

我試圖在UITableViewCell中有一個標籤,可以跨越兩條線,但是如果只有一條線與第一條線垂直對齊。UITableViewCell不中繼/重新繪製

解決標籤高度(下面)的代碼似乎可行,但標籤沒有獲得重新佈置/重新繪製。如果我將該單元格從視圖中滾動並返回,則標籤具有正確的高度。

我試過[cell setNeedsLayout],[cell setNeedsDisplay],[titleLabel setNeedsLayout][titleLabel setNeedsLayout,沒有組合已經起作用。

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

    Item *item = (self.items)[indexPath.section][indexPath.row]; 

    UILabel *titleLabel = (UILabel *)[cell viewWithTag:100]; 
    titleLabel.text = item.title; 
    titleLabel.backgroundColor = [UIColor redColor]; 

    // Some titles span two lines, so resize to fit the new content. 

    CGRect textRect = [titleLabel.attributedText boundingRectWithSize:CGSizeMake(titleLabel.frame.size.width, CGFLOAT_MAX) options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) context:nil]; 
    CGRect labelRect = CGRectIntegral(CGRectMake(titleLabel.frame.origin.x, 
              titleLabel.frame.origin.y, 
              titleLabel.frame.size.width, 
              textRect.size.height)); 
    NSLog(@"%@, %f", titleLabel.text, labelRect.size.height); // This logs out the correct height 

    titleLabel.frame = labelRect; 

    return cell; 
} 
+0

原來我使用自動佈局,這意味着我無法直接設置框架。相反,我需要添加一個高度約束,並將其連接到我的'UITableViewCell'子類上的IBOutlet。 – ICR

+1

你的'cell'是'UITableViewCell'的一個實例,還是它的一個子類?您可能想嘗試編寫自己的'UITableViewCell'子類並覆蓋'layoutSubviews'方法? – Romain

回答

0

原來我使用自動佈局,這意味着我無法直接設置框架。相反,我需要添加高度約束,並將其連接到我的UITableViewCell子類上的IBOutlet

0

請試試我的建議。可能會幫助你在UITableview中使用單元的可重用性。請在您的代碼中檢查以下幾點:

  1. 如果您在Cell中重繪UITableView的時候如何處理cell == nil。這就是爲什麼你必須使下面的條件爲UITableViewCell的可重用性。

    // Get table View Cell 
    static NSString *CellIdentifier = @"ItemCell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    
    if (cell == nil) { 
    
        NSArray *nib; 
        nib = [[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil]; 
        cell = (UITableViewCell *) [nib objectAtIndex:0]; 
    } 
    

請測試它,讓我知道。

+0

我使用Storyboard,它自動分配新的單元格,所以我不需要檢查零。 – ICR