2015-09-30 184 views
6

私は私のUITableViewに2つのセクションを持っています。
最初のセクションで複数のセルを選択できるようにし、2番目のセクションで1つの選択のみを許可します。
私はいくつかのコードを試しましたが、うまく機能しませんでした。
できるだけ早くコードを入力してください。ありがとうございました。UITableView - 複数選択と単一選択

enter image description here

+0

についてあなたは二行が選択された場合に、第2節では、最初の行の選択を解除しますか?また、既存のコードを投稿すると役立ちます。 – Caleb

答えて

4

おそらく、あなたが実装できるテーブルビューのデリゲートメソッド:

tableView(_:shouldHighlightRowAtIndexPath:)

tableView(_:didSelectRowAtIndexPath:) ...と判断した場合は(indexPath.rowindexPath.sectionから)関連するセクションはsをサポートします"0セクションは複数選択をサポートしていますが、セクション1はサポートしていません")、単一選択のみをサポートしている場合は、選択された行が既に存在するかどうかをチェックしますtableView.indexPathsForSelectedRows)。

選択された行がすでに存在する場合は、あなたがすることができます:tableView(_:shouldHighlightRowAtIndexPath:)から

  1. 戻りfalse、および
  2. tableView(_:didSelectRowAtIndexPath:)から何も(ちょうどreturn)を行いませんに(私は、このメソッドが実際に呼び出されたかどうかわからないんだけどfalseshouldHighlight...から返すと、おそらくそれをチェックします)。
0

セクション2で選択した行を新しい選択行にする場合は、これが有効です。それ以外の場合、@ NicolasMiariの答えに従ってください。

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
    if indexPath.section == 1 { 
     for i in 0..tableView.numberOfRowsInSection(indexPath.section) - 1 { 
      let cell: UITableViewCell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: i, inSection: indexPath.section))! 
      if (i == indexPath.row) { 
       cell.accessoryType = .Checkmark 
       cell.selected = false 
      } 
      else { 
       cell.accessoryType = .None 
      } 
     } 
    } 
    else { 
     //Do whatever for the first section 
    } 
} 

非常にエレガントではありませんが、うまくいけばそれはあなたにアイデアを与えるでしょう。

2

これは簡単に試すことができます。このソリューションは私にとって完璧に機能します。 ...それは多分しようと他人のために働い与える

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
    if indexPath.section == 0 { 
     if let cell = tableView.cellForRowAtIndexPath(indexPath) { 
      cell.accessoryType = .Checkmark 
     } 
    } 
    else { 
     if let cell = tableView.cellForRowAtIndexPath(indexPath) { 
      cell.accessoryType = .Checkmark 
     } 
    } 
} 

func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) { 
    if indexPath.section == 1 { 
     if let cell = tableView.cellForRowAtIndexPath(indexPath) { 
      cell.accessoryType = .None 
     } 
    } 
} 

編集:スウィフト-4

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
    if indexPath.section == 0 { 
     if let cell = tableView.cellForRow(at: indexPath) { 
      cell.accessoryType = .checkmark 
     } 
    } 
    else { 
     if let cell = tableView.cellForRow(at: indexPath) { 
      cell.accessoryType = .checkmark 
     } 
    } 
} 

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { 
    if indexPath.section == 1 { 
     if let cell = tableView.cellForRow(at: indexPath as IndexPath) { 
      cell.accessoryType = .none 
     } 
    } 
} 
関連する問題