我想创建一个自定义的 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;
这为 UITableViewCell 子类提供了一个请求 URL,该子类在 setRequestURL
方法中处理加载。
在 FavouriteCell 类中,我保留了 initWithStyle:reuseIdentifier:
方法,在 Nib 中,我将 FavCellIdentifier 设置为标识符,将 FavouriteCell 设置为类。现在如何让 FavouriteCell 类加载 Nib?
最佳答案
为了使用 nib/xib 文件,您将不得不以不同的方式实例化 FavouriteCell
。
试试这个:
- 确保您已将
UITableViewCell
的类型更改为FavouriteCell
的子类,而不是默认的UITableViewCell
在你的 xib 中。通过以下方式执行此操作:- 单击 Interface Builder 对象 Pane 中的单元格。
- 然后,转到 Identity Inspector 选项卡并确保 Custom Class 下的 Class 选择列出
FavouriteCell
。
- 将
File's Owner
属性更改为要在其中显示自定义UITableViewCell
的UIViewController
(与步骤 #1 几乎相同的过程). - 将
FavouriteCell
类型的IBOutlet
属性添加到您的UIViewController
。随意命名(我打算将其命名为cell
)。 - 返回
UITableViewCell
的 xib,将 File's Owner 中cell
属性的 IBOutlet 连接到您的自定义UITableViewCell
。 - 使用此代码以编程方式加载单元格:
- (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;
}
关于ios - 使用自己的 Nib 子类化 UITableViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10411409/