簡體   English   中英

使用自己的Nib對UITableViewCell進行子類化

[英]Subclassing UITableViewCell with its own Nib

我想創建一個自定義UITableViewCell子類,使用URL連接異步加載內容。 我有一個處理所有這些的UITableViewCell子類和一個定義單元格布局的Nib文件,但是我在連接這兩個時遇到了麻煩。 這是我在tableView:cellForRowAtIndexPath使用的代碼tableView:cellForRowAtIndexPath

static NSString *FavCellIdentifier = @"FavCellIdentifier";

FavouriteCell *cell = [tableView dequeueReusableCellWithIdentifier:FavCellIdentifier];

if (cell == nil)
{
    cell = [[[FavouriteCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:FavCellIdentifier] autorelease];
}

cell.requestURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@?%@=%i", URL_GET_POST_STATUS,
                                           URL_PARAM_SERIAL,
                                           [[self.favourites objectAtIndex:indexPath.row] intValue]]];

return cell;

這為UITableViewCell子類提供了一個請求URL,該子類處理setRequestURL方法中的加載。

在FavouriteCell類中,我按原樣保留了initWithStyle:reuseIdentifier:方法,並且在Nib中我將FavCellIdentifier設置為標識符,並將FavouriteCell設置為類。 現在我如何讓FavouriteCell類加載Nib?

為了使用nib / xib文件,您將不得不以不同方式實例化FavouriteCell

試試這個:

  1. 確保您已將UITableViewCell類型更改為FavouriteCell的子類,而不是xib中的默認UITableViewCell 這樣做:
    • 單擊Interface Builder的對象窗格中的單元格。
    • 然后,轉到Identity Inspector選項卡,確保Custom Class下的Class選擇列出FavouriteCell
  2. File's Owner屬性更改為要在其中顯示自定義UITableViewCellUIViewController (與步驟#1完全相同的過程)。
  3. 將類型為FavouriteCellIBOutlet屬性添加到UIViewController 把它命名為你喜歡的(我將其稱為cell )。
  4. 回到UITableViewCell的xib,將文件所有者中的cell屬性的IBOutlet連接到自定義UITableViewCell
  5. 使用此代碼以編程方式加載單元格:

- (FavouriteCell *)tableView:(UITableView *)tableView 
       cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellId = @"FavCellId";
    FavouriteCell *cell = [tableView dequeueReusableCellWithIdentifier:CellId];
    if (!cell) {
        // Loads the xib into [self cell]
        [[NSBundle mainBundle] loadNibNamed:@"FavouriteCellNibName" 
                                      owner:self 
                                    options:nil];
        // Assigns [self cell] to the local variable
        cell = [self cell];
        // Clears [self cell] for future use/reuse
        [self setCell:nil];
    }
    // At this point, you're sure to have a FavouriteCell object
    // Do your setup, such as...
    [cell setRequestURL:[NSURL URLWithString:
                  [NSString stringWithFormat:@"%@?%@=%i", 
                      URL_GET_POST_STATUS, 
                      URL_PARAM_SERIAL, 
                      [[self.favourites objectAtIndex:indexPath.row] intValue]]
     ];
    return cell;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM