繁体   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