非表示ということはできないのでセルから削除することになると思います。
とりあえず以下のコードでStoryboard
を設定すると、ボタン押下でセルがアニメーションして削除されます。
※ 削除されたセルはボタンが見えないので再度押下して表示することはできません、このところはどのように考えていますか?
swift
1import UIKit
2
3class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, CustomCellDelegate {
4
5 @IBOutlet weak var tableView: UITableView!
6
7 // Section Data
8 let sectionTitleArray = ["Section-1", "Section-2", "Section-3"]
9
10 // Data Array
11 var dataArray1 = [Model("A"), Model("B"), Model("C", isShowButton: true), Model("D"), Model("E")]
12 var dataArray2 = [Model("1"), Model("2"), Model("3")]
13 var dataArray3 = [Model("a"),Model("b"),Model("c"),Model("d")]
14 var dataArrayGroup: [[Model]] = []
15
16 override func viewDidLoad() {
17 super.viewDidLoad()
18
19
20 // Make Data
21 dataArrayGroup.append(dataArray1)
22 dataArrayGroup.append(dataArray2)
23 dataArrayGroup.append(dataArray3)
24
25 tableView.estimatedRowHeight = 20
26 tableView.rowHeight = UITableViewAutomaticDimension
27 }
28
29
30 // MARK: - TableView Delegate & DataSource
31
32 func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
33 return sectionTitleArray[section]
34 }
35
36 // Section Count
37 func numberOfSectionsInTableView(tableView: UITableView) -> Int {
38 return dataArrayGroup.count
39 }
40
41 // Row Count
42 func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
43 return dataArrayGroup[section].count
44 }
45
46
47 // Generate Cell
48 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
49 let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! CustomCell
50 cell.textLabel?.text = dataArrayGroup[indexPath.section][indexPath.row].text
51 cell.closeButton.hidden = !dataArrayGroup[indexPath.section][indexPath.row].isShowButton
52 cell.delegate = self
53 cell.cellIndexPath = indexPath
54 cell.textLabel?.backgroundColor = UIColor.clearColor()
55 return cell
56 }
57
58 func pushDeleteAction(indexPath: NSIndexPath) {
59 dataArrayGroup[indexPath.section].removeAtIndex(indexPath.row)
60 tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
61 }
62}
63
64struct Model {
65 var text = ""
66 var isShowButton = false
67
68 init(_ text: String, isShowButton: Bool = false) {
69 self.text = text
70 self.isShowButton = isShowButton
71 }
72}
73
74protocol CustomCellDelegate: class {
75 func pushDeleteAction(indexPath: NSIndexPath)
76}
77
78
79class CustomCell: UITableViewCell {
80
81 var cellIndexPath: NSIndexPath!
82 weak var delegate: CustomCellDelegate!
83 @IBOutlet weak var closeButton: UIButton!
84
85 @IBAction func pushCloseButton(sender: UIButton) {
86 delegate?.pushDeleteAction(cellIndexPath)
87 }
88}
回答追記 サンプル
teratail_45367 サンプル
中にプロジェクトが2つ入っていてteratail_45367-1
の方がデータを削除、追加しているものでteratail_45367-2
がセルの高さを変更しているものです。
参考にしてみてください。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/08/24 05:11
2016/08/24 20:25 編集
2016/08/25 01:00