![](/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.