![](/img/trans.png)
[英]iOS: UITableViewCell subclassing with nib, into UIView (not view controller) subclass
[英]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
。
试试这个:
UITableViewCell
的类型更改为FavouriteCell
的子类,而不是xib中的默认UITableViewCell
。 这样做:
FavouriteCell
。 File's Owner
属性更改为要在其中显示自定义UITableViewCell
的UIViewController
(与步骤#1完全相同的过程)。 FavouriteCell
的IBOutlet
属性添加到UIViewController
。 把它命名为你喜欢的(我将其称为cell
)。 UITableViewCell
的xib,将文件所有者中的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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.