使用自己的Nib对UITableViewCell进行子类化

ben*_*wad 3 interface-builder uitableview ios

我想创建一个自定义UITableViewCell子类,使用URL连接异步加载内容.我有一个处理所有这些的UITableViewCell子类和一个定义单元格布局的Nib文件,但是我在连接这两个时遇到了麻烦.这是我正在使用的代码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;
Run Code Online (Sandbox Code Playgroud)

这为UITableViewCell子类提供了一个请求URL,该子类处理setRequestURL方法中的加载.

在FavouriteCell类中,我保持initWithStyle:reuseIdentifier:方法不变,并且在Nib中我将FavCellIdentifier设置为标识符,将FavouriteCell设置为类.现在我如何让FavouriteCell类加载Nib?

mbm*_*414 7

为了使用nib/xib文件,您将不得不以FavouriteCell不同方式实例化它.

试试这个:

  1. 请确保你已经修改了类型你的UITableViewCell的是一个子类FavouriteCell,而不是默认UITableViewCell在您的厦门国际银行.这样做:
    • 单击Interface Builder的对象窗格中的单元格.
    • 然后,转到Identity Inspector选项卡并确保Custom Class列下的Class选择FavouriteCell.
  2. File's Owner属性更改为UIViewController您要显示自定义的位置UITableViewCell(与步骤#1几乎相同).
  3. 添加IBOutlet类型的属性FavouriteCell到您的UIViewController.把它命名为你喜欢的(我打算称之为cell).
  4. 回到xib中UITableViewCell,将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;
}
Run Code Online (Sandbox Code Playgroud)