@@ -13,7 +13,13 @@ class ViewController: UIViewController {
1313
1414 @IBOutlet weak var tableView : UITableView !
1515
16- fileprivate var messages : [ MessageModel ] = [ ]
16+ private var sections : [ [ MessageModel ] ] = ( 1 ... 10 )
17+ . map { i -> [ MessageModel ] in
18+ ( 0 ..< i)
19+ . map {
20+ MessageModel ( imageName: " marty1 " , message: " \( $0) hello " , time: " 00:00 " )
21+ }
22+ }
1723
1824 override func viewDidLoad( ) {
1925 super. viewDidLoad ( )
@@ -39,28 +45,43 @@ class ViewController: UIViewController {
3945 }
4046
4147 @IBAction func addButtonTapped( _ sender: UIBarButtonItem ) {
48+ let i = sections. count - 1
49+ var messages = sections [ i]
4250 messages. append ( MessageModel ( ) )
51+ sections [ i] = messages
4352 tableView. beginUpdates ( )
44- tableView. re. insertRows ( at: [ IndexPath ( row: messages. count - 1 , section: 0 ) ] , with: . automatic)
53+ tableView. re. insertRows ( at: [ IndexPath ( row: messages. count - 1 , section: i ) ] , with: . automatic)
4554 tableView. endUpdates ( )
4655 }
4756
4857 @IBAction func trashButtonTapped( _ sender: UIBarButtonItem ) {
49- messages . removeAll ( )
58+ sections . removeLast ( max ( 0 , sections . count - 1 ) )
5059 tableView. reloadData ( )
5160 }
5261}
5362
5463extension ViewController : UITableViewDataSource {
64+
65+ func numberOfSections( in tableView: UITableView ) -> Int {
66+ sections. count
67+ }
68+
5569 func tableView( _ tableView: UITableView , numberOfRowsInSection section: Int ) -> Int {
56- return messages . count
70+ sections [ section ] . count
5771 }
5872
5973 func tableView( _ tableView: UITableView , cellForRowAt indexPath: IndexPath ) -> UITableViewCell {
6074 let cell = tableView. dequeueReusableCell ( withIdentifier: " Cell " , for: indexPath)
75+ let messages = sections [ indexPath. section]
6176 ( cell as? TableViewCell ) ? . configure ( with: messages [ indexPath. row] )
6277 return cell
6378 }
79+
80+ func tableView( _ tableView: UITableView , willDisplay cell: UITableViewCell , forRowAt indexPath: IndexPath ) {
81+ let messages = sections [ indexPath. section]
82+ let message = messages [ indexPath. row]
83+ print ( " willDisplay: \( message) " )
84+ }
6485}
6586
6687
0 commit comments