2015-12-22 98 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一樣,可以將單元格標識符作爲枚舉,並將特定行存儲爲數組中的枚舉實例。然後你的開關就在存儲在數組行索引處的枚舉值上。