![](/img/trans.png)
[英]Custom UITableViewCell without dequeueReusableCellWithIdentifier
[英]UITableViewCell style and dequeueReusableCellWithIdentifier
所以我注冊了我的手機:
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// setting up the cell
}
問題是我無法設置cell.detailTextLabel.text
屬性。 細胞永遠不會是nil
。
如果首先調用,則表視圖registerClass
將使dequeueReusableCellWithIdentifier
在單元重用標識符匹配時返回非零單元。
我相信registerClass通常用於將是從UITableViewCell
派生的自定義單元格的單元格。 您的自定義單元格可以覆蓋initWithStyle並在那里設置樣式。
並不總是需要創建自定義單元格。
如果要設置單元格樣式,請不要調用registerClass
。
您需要做3次更改才能實現目標:
通常有兩種方法可以用subtile創建單元格,首先使用自定義UITableViewCell,在init中設置樣式。 其次是跟隨代碼,這是你想要的:
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
嘗試為單元格使用UITableViewCellStyleSubtitle樣式。 將if語句中的行更改為:
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
您需要更改單元格樣式:
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
對此
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
這對你有用。
最簡單的方法是使用故事板,並在IB中設置單元格樣式。 在這種情況下,您不應該注冊任何內容,也不應該有if(cell == nil)子句。 您是否使用dequeueReusableCellWithIdentifier:或dequeueReusableCellWithIdentifier:forIndexPath似乎並不重要。 當故事板中創建該單元格時,它們都保證返回單元格。
創建自定義單元格。 在界面構建器中更改其樣式。 使用表視圖從視圖控制器的nib中注冊單元格。
和代碼:
- (void)viewDidLoad {
[super viewDidLoad];
[self.tableView registerNib:[UINib nibWithNibName:@"YourCustomCell" bundle:nil] forCellReuseIdentifier:kReuseIdentifier];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
YourCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseIdentifier];
// Do things with the cell.
// The cell has no chance to be nil because you've already registered it in viewDidLoad method.
// So there's not need to write any code like if(cell==nil).
// Just use it.
return cell;
}
這是一個老問題。 我只是想提供一種替代解決方案。
注冊單元格后,為什么不在下面嘗試:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
然后做:
[cell initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier ];
這個對我有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.