2015-12-22 101 views
0

如果我想在Objective-C中创建一个表格视图,并且每个单元格的定制方式不同,我会创建多个原型单元格,对其进行自定义,并设置它们各自的标识符。然后,我会添加此代码,以便单元格将显示我如何定制它。显示原型单元格

- (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; 
} 

现在我更新我的应用程序斯威夫特2,想知道如何编写上面应该改变在斯威夫特工作2.感谢!

+3

只是在Swift语法中。另外你可以添加Enum for Cell Identifiers。 – sunshinejr

回答

1

在这里你去:

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一样,可以将单元格标识符作为枚举,并将特定行存储为数组中的枚举实例。然后你的开关就在存储在数组行索引处的枚举值上。