2015-04-02 76 views
7

我使用一個UITableView,用3段(靜態細胞)對號靜態細胞的UITableView

  • 貨幣
  • 語言
  • 社會

他們有不同的行數:

  • 貨幣有3行(USD,EUR,JPY)
  • 語言有兩行(EN,JP)
  • 社會有3行(Twitter的,FB,線)

現在,我已經在默認情況下,在每節的第一行設置一個複選標記。不過,我希望允許用戶設置其默認設置,並根據他們設置的內容相應地更改對號。

我的問題是如何設置3個不同部分的複選標記,每個部分的行數不同?

我是否需要爲每個部分設置一個單元標識符?我是否也需要爲每個Section創建一個UITableViewCell swift文件?

回答

12

如果選中標記響應設置爲攻的小區,只需要實現tableView(_:didSelectRowAtIndexPath:)

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
    let section = indexPath.section 
    let numberOfRows = tableView.numberOfRowsInSection(section) 
    for row in 0..<numberOfRows { 
     if let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: row, inSection: section)) { 
      cell.accessoryType = row == indexPath.row ? .Checkmark : .None 
     } 
    } 
    // ... update the model ... 
} 

否則,你可以在你的故事板的每個細胞集標識符(或網點,如果你喜歡,因爲細胞不重複使用),然後以編程方式設置複選標記。例如,使用一個委託方法:

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { 
    if let identifier = cell.reuseIdentifier { 
     switch identifier { 
      "USD Cell": cell.accessoryType = model.usdChecked ? .Checkmark : .None 
      "EUR Cell": cell.accessoryType = model.eurChecked ? .Checkmark : .None 
      //... 
      default: break 
     } 
    } 
} 

不應該有必要建立用於每個部分/小區的單獨的子類。

+0

這看起來像它會工作,+1。如果每節只能有1個複選標記,那我應該怎麼做?語言設置不能同時爲EN和JP。貨幣只能是美元或歐元或日元。 – Gino 2015-04-02 10:25:33

+1

@Gino我已經更新了第一個代碼示例,僅在給定部分中最後一次敲擊的單元格旁邊放置了複選標記。它只是列舉了挖掘部分中的表格視圖單元格,並確保只有敲擊的行具有複選標記。 – Stuart 2015-04-02 14:45:46

+0

哦哇,這是我在O'Reilly Swift書中找不到的新東西。非常感謝你的配偶。 +1 – Gino 2015-04-02 14:51:56

1

只是一個快速更新斯威夫特3:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
     let section = indexPath.section 
     let numberOfRows = tableView.numberOfRows(inSection: section) 
     for row in 0..<numberOfRows { 
      if let cell = tableView.cellForRow(at: IndexPath(row: row, section: section)) { 
       cell.accessoryType = row == indexPath.row ? .checkmark : .none 
      } 
     } 
}