展示原型细胞
Showing the prototype cells
如果我想在 Objective-C 中创建一个 table 视图,每个单元格都以不同方式自定义,我会创建多个原型单元格,对其进行自定义,然后为每个单元格设置自己的标识符。然后我会添加这段代码,这样单元格就会完全按照我自定义的方式显示。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
switch ( indexPath.row )
{
case 0:
CellIdentifier = @"fj";
break;
case 1:
CellIdentifier = @"pg";
break;
}
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: CellIdentifier forIndexPath: indexPath];
return cell;
}
我现在正在将我的应用程序更新到 Swift 2,并且想知道如何更改上面的代码以在 Swift 2 中工作。谢谢!
给你:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cellIdentifier: String
switch indexPath.row {
case 0:
cellIdentifier = "fj"
case 1:
cellIdentifier = "pg"
default:
cellIdentifier = "Cell"
}
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath)
return cell
}
您会注意到语法非常相似,函数调用遵循与 Objective-C 版本相同的格式。要稍微清理一下,就像@sunshine 提到的那样,您可以将单元格标识符作为一个枚举,并将特定的行作为该枚举的实例存储在一个数组中。然后你的开关就在存储在数组中行索引处的枚举值上。
如果我想在 Objective-C 中创建一个 table 视图,每个单元格都以不同方式自定义,我会创建多个原型单元格,对其进行自定义,然后为每个单元格设置自己的标识符。然后我会添加这段代码,这样单元格就会完全按照我自定义的方式显示。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
switch ( indexPath.row )
{
case 0:
CellIdentifier = @"fj";
break;
case 1:
CellIdentifier = @"pg";
break;
}
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: CellIdentifier forIndexPath: indexPath];
return cell;
}
我现在正在将我的应用程序更新到 Swift 2,并且想知道如何更改上面的代码以在 Swift 2 中工作。谢谢!
给你:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cellIdentifier: String
switch indexPath.row {
case 0:
cellIdentifier = "fj"
case 1:
cellIdentifier = "pg"
default:
cellIdentifier = "Cell"
}
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath)
return cell
}
您会注意到语法非常相似,函数调用遵循与 Objective-C 版本相同的格式。要稍微清理一下,就像@sunshine 提到的那样,您可以将单元格标识符作为一个枚举,并将特定的行作为该枚举的实例存储在一个数组中。然后你的开关就在存储在数组中行索引处的枚举值上。