2011-06-12 34 views
1

如何使UIView添加到UITableViewCell內容視圖適合其範圍內?如何使UIView添加到UITableViewCell內容視圖適合其範圍內?

也就是說,我創建了一個單獨的NIB文件(上面有3個標籤),並且想用它來顯示UITableView中的每個單元格。我在cellForRowAtIndexPath方法中添加了自定義的基於NIB的視圖到單元格的內容視圖,但是我所看到的最終結果是一(1)個自定義的基於NIB的視圖(不像我期望的那樣在tableview中是多個視圖)。

我該如何安排,以便每個自定義視圖適合每個UITableViewCell內整齊?另請注意,自定義NIB視圖中的標籤具有自動換行。

我是否需要爲自定義NIB視圖創建一個框架,但在那種情況下,我並不確定如何設置座標。它會相對於UITableViewCell嗎?如果自定義視圖高度可以由於它的UILabel自動換行而改變,那麼我假設我需要單獨在UITableView中手動計算這個高度? (也許我應該去動態/自定義視圖的創建和刪除使用InterfaceBuilder中/ NIB)的概念

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 
    } 

    UIView *detailedView = [[[NSBundle mainBundle] loadNibNamed:@"DetailedAppointView" owner:self options:nil] objectAtIndex:0]; 
    [cell.contentView addSubview:detailedView]; // DOESN'T SEE TO WORK 

    return cell; 
} 

回答

1

這是我要做的事,如果我需要實現一個自定義的UITableViewCell。

我爲我的自定義單元格ex創建了UITableViewCell的子類。 「MyCustomCell」。然後我爲它創建一個NIB文件,並在此NIB文件中插入UITableViewCell並將其類型更改爲「MyCustomCell」,並給它一個與類名稱相同名稱的標識符。然後我將所有的子視圖都插入到我的單元格中。全部在IB。

我得到了我的手機拉皮條了我的likning後:-)我在下面的方式來使用它:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"MyCustomCell"; 
    static NSString *CellNib = @"MyCustomCell"; 

    MyCustomCell *cell = (MyCustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     NSArray *nib = [[NSBundle mainBundle] loadNibNamed:CellNib owner:self options:nil]; 
     cell = (MyCustomCell *)[nib objectAtIndex:0]; 
    } 

    //Manipulate your custom cell here 

    return cell; 
} 
+0

感謝 - 那麼,這是否意味着我需要一個自定義的UI細胞MyCustomCell.m和MyCustomCell.h檔案呢?即目前我只創建了一個NIB文件視圖,並試圖讓事情只用這個工作。 – Greg 2011-06-12 22:58:56

+0

是的,你必須有一種方法來訪問添加到你的自定義MyCustomCell中的自定義UIComponent。因此,創建MYCustomCell.m和MyCustomCell.h將代碼中的對象與NIB和VIOLA中的對象關聯起來! – Cyprian 2011-06-13 08:46:51