iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 13
0
Software Development

挑戰 30天內送審一支APP 系列 第 13

UIAlertController 與 tableview 之互動 (三)( D day + 12 )

這次我們希望可以新加一個功能,在建立的表單中把去過的餐廳做記號。
跟昨天一樣用 closure 的寫法,並且把程式碼放在 tableView(_:didSelectRowAt:) 方法中。

// add check-in
            let checkInAction = UIAlertAction(title:"check in", style: .default , handler:
            {
                (action:UIAlertAction!) -> Void in
                
                let cell = tableView.cellForRow(at: indexPath)
                cell?.accessoryType = .checkmark
                
            })
            optionMenu.addAction(checkInAction)

完成後按下” Run “ 。

實際操作的時候發現,當check-in “Coffee deadens” 時,”Traif” 同時被勾選了。為什麼會這樣呢? 還記得一開始我們創建 optionMenu 時用到 “dequeueReusableCell”, cell在記憶體內會一直不斷的被循環利用,但是我們在處理 checkmark 時卻沒有做到回收的機制,想一下要怎樣處理呢?
可以建立一個陣列來記錄每一個cell是否被checkin過!
先在 RestaurantTabileViewController 宣告一個 Bool 陣列

var restaurantIsVisited = Array(repeating:false,count:(21))

當餐廳被勾選過後,需要將這筆資料更新到剛剛建立的陣列 ( RestaurantIsVisited) 中,因此要在 // add check-in 加上一段程式碼來更新資料

self.restaurantIsVisited[indexPath.row] = true

當資料被更新時,介面也會跟著變動。
但是這次要將程式碼加在 tableView(_:cellForRowAt:)

	//Reflash and update the checkmark
  if restaurantIsVisited[indexPath.row] {
                cell.accessoryType = .checkmark
            } else {
                cell.accessoryType = .none
            }

上一篇
UIAlertController 與 tableview 之互動 (二) ( D day + 11 )
下一篇
UIAlertController 與 tableview 之互動 (四)( D day + 13 )
系列文
挑戰 30天內送審一支APP 30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言