![](/img/trans.png)
[英]Custom UITableViewCell without dequeueReusableCellWithIdentifier
[英]UITableViewCell dequeueReusableCellWithIdentifier with custom initializer
我正在使用[UITableView registerClass: forReuseIdentifier:]
和[UITableView dequeueReusableCellWithIdentifier:]
來排隊和出列UITableViewCells。
例如,在viewDidLoad中:
[self.storeTableView registerClass:[StoreLineGraphCell class] forCellReuseIdentifier:@"StoreLineGraphCellIdentifier"];
在cellForRowAtIndexPath中:
StoreLineGraphCell *cell = (StoreLineGraphCell*)[self.storeTableView dequeueReusableCellWithIdentifier:@"StoreLineGraphCellIdentifier"];
在這樣做時,為initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
調用initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
初始值設定項。 問題是我需要使用自定義初始化程序來創建具有必要選項的單元格。 例如,能夠做這樣的事情:
StoreLineGraphCell *cell = [[StoreLineGraphCell alloc] initWithReuseIdentifier:@"StoreLineGraphCell" isLocked:YES isUpcoming:YES];
registerClass
和dequeue
模式似乎不可能這樣。 我想把它保存在初始化程序中,因為它應該只運行一次,而不是每次單元格出列時。 有沒有正確的方法來實現這一目標?
當你遵循通常的單元重用模式時(就像你使用寄存器類和出隊一樣),我看不到一種易於實現的方法。
如果我是你,我會創建一個額外的初始化方法(不遵循通常的obj-c init
模式)或簡單地設置並在dequeueReusableCellWithIdentifier
調用之后調用它。
StoreLineGraphCell *cell = (StoreLineGraphCell*)[self.storeTableView dequeueReusableCellWithIdentifier:@"StoreLineGraphCellIdentifier"];
[cell furtherInitWithLocked:YES andUpcoming:NO]; // ... or so
您正在使用正確的registerClass和dequeue方法,但是為了調用/設置自定義屬性,您應該配置創建單獨的方法並調用它。
而不是這個:
StoreLineGraphCell *cell = [[StoreLineGraphCell alloc]
initWithReuseIdentifier:@"StoreLineGraphCell" isLocked:YES isUpcoming:YES];
你可以這樣做:
StoreLineGraphCell *cell = // get the dequeue cell
[cell configure];
在configure方法中,您可以設置屬性,如下所示:
-(void) configure
{
self.isLocked = YES;
self.isUpcoming = YES;
}
這是我今天遇到的一個常見問題。
但是,它可以像這樣解決。
因為在dequeueReusableCellWithIdentifier
方法調用之前注冊的單元類,在執行之后
cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier]
,
單元格總是不是零並且返回
- initWithStyle:style reuseIdentifier:reuseIdentifier
。
看來您無法自定義自己的init方法。
但是,如果您之前沒有注冊單元類,那么如果tableview沒有可重用的單元格,則dequeueReusableCellWithIdentifier
將返回nil 。
因此,我們應該檢查dequeueReusableCellWithIdentifier
返回的單元格值,如果它是nil,那么我們可以使用我們的自定義方法初始化它。
cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier]
if (!cell) {
cell = /* custom init method */
}
那已經完成了! 如果我們要自定義子類cell init方法,那么之前不要注冊cell類 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.