現在、UITableViewを使ってヘッダをタップして開閉式のmenuを作成しようとしているのですが、どうにもわかりません。
セクションのviewにタップジェスチャーを追加して、タップイベントで対象のセクションをreloadSections()でcellの数を読み込ませて作成する・・・といったことをしたいです。しかし一番最初のタップはうまく作動して、想定通りのcell数を作成して表示するのですが、二度目に他のヘッダをタップすると落ちてしまいます。一度目と同じヘッダならば落ちることはないのですが・・・
現状のコードを載せます。
Xcode7.31
swift
Swift
1 2import UIKit 3 4class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource { 5 6 var tableView = UITableView() 7 8 var selectedIndex:Int? = nil 9 10 //セクションのタイトルと、cellに表示したい内容をtapleで用意 11 let contents = [("A",["1","2","3"]),("B",["1","2","3","4","5","6","7","8"]),("C",["1","2"]),("D",["1","2","3"]),("E",["1","2","3","4"]),("F",["1","2"])] 12 13 override func viewDidLoad() { 14 super.viewDidLoad() 15 16 } 17 18 override func viewWillAppear(animated: Bool) { 19 20 tableView.frame = CGRectMake(0,0,200,500) 21 tableView.dataSource = self 22 tableView.delegate = self 23 24 self.view.addSubview(tableView) 25 } 26 27 func numberOfSectionsInTableView(tableView: UITableView) -> Int { 28 29 return contents.count 30 } 31 32 33 34 //セクションの高さを指定 35 func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { 36 return 40 37 } 38 39 //セクションの編集 40 func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { 41 42 let sectionView = UIView(frame:CGRectMake(0,0,self.view.frame.width,40)) 43 sectionView.backgroundColor = UIColor.whiteColor() 44 sectionView.tag = section 45 46 //セクションにタイトル設定 47 let sectionLabel = UILabel(frame:CGRectMake(10,20,self.view.frame.width,20)) 48 sectionLabel.text = contents[section].0 49 50 //セクションにタップジェスチャーを追加 51 sectionView.addGestureRecognizer(UITapGestureRecognizer(target: self,action:#selector(sectionTapAction(_:)))) 52 53 sectionView.addSubview(sectionLabel) 54 55 return sectionView 56 } 57 58 59 60 //セルの個数を指定する 61 func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 62 63 if selectedIndex == nil{ 64 return 0 65 } 66 else{ 67 68 if selectedIndex! == section{ 69 70 return self.contents[section].1.count 71 72 }else{ 73 return 0 74 } 75 76 } 77 } 78 79 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 80 81 let cell: UITableViewCell = UITableViewCell() 82 cell.frame = CGRectMake(0,0,200,50) 83 84 let label = UILabel(frame:CGRectMake(0,0,100,40)) 85 label.text = contents[selectedIndex!].1[indexPath.row] 86 87 return cell 88 } 89 90 91 92 93 func sectionTapAction(sender:UITapGestureRecognizer){ 94 95 96 self.selectedIndex = sender.view!.tag 97 98 self.tableView.reloadSections(NSIndexSet(index: self.selectedIndex!), withRowAnimation: .None) 99 100 101 } 102 103 104 override func didReceiveMemoryWarning() { 105 super.didReceiveMemoryWarning() 106 // Dispose of any resources that can be recreated. 107 } 108 109} 110
自分なりにいろいろ調べてみたのでが、何が問題なのかわかりませんでした。拙い文章で質問の意図が伝わるか不安ですが、お知恵を拝借できれば幸いです。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/09/20 13:05