看板 MacDev 關於我們 聯絡資訊
最近開始看書自學 xcode (swift) 之前沒有其他基礎,學得有點辛苦 書籍:ios 10 app 程式設計實力超進化攻略 現在學到UIAlertController 裡面有一段閉包的應用說明: let callActionHandler = { (action:UIAlertAction!) -> Void in let alertMessage = UIAlertController(title: "Service Unavailable", message: "Sorry, the call feature is not available yet. Please retry later.", preferredStyle: .alert) alertMessage.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(alertMessage, animated: true, completion: nil ) } 書中又教了另一種形式 (上面說推薦,比較簡潔) 但是不是用上面那個設定去介紹 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) 我想了一個晚上一直沒有將第一種轉成第二種的形式 想請問各位該如何將第一種轉成下面那種比較簡潔的語法 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 118.160.60.120 ※ 文章網址: https://www.ptt.cc/bbs/MacDev/M.1493736350.A.DBD.html
darktt: 這寫法不都一樣,而且下面的方法並沒有比較簡潔 05/03 05:57
Polestar: 第一個是把handler的部分另外寫,第二個是直接寫在一起 05/03 13:24
Polestar: 第一個看起來比較複雜是因為他裡面還多一個彈出框的功 05/03 13:29
Polestar: 能 05/03 13:29
Polestar: 要寫成第二種就是把你第一段的部分直接塞到callAction 05/03 13:33
Polestar: 裡面的handler 05/03 13:33
vicjoyce0328: 上面的callActionHandler 只是(UIAlertAction)-> V 05/03 16:23
vicjoyce0328: oid 05/03 16:23
vicjoyce0328: 當你要設定一個UIActionAlert 時,把它當成參數傳進 05/03 16:24
vicjoyce0328: 去 05/03 16:24
vicjoyce0328: 例如: let callAction = UIAlertAction(title:"fo 05/03 16:27
vicjoyce0328: o",style:.default, handler: callActionHandler) 05/03 16:27
vicjoyce0328: 而下面的就是一般寫法 05/03 16:28
vicjoyce0328: 我是認為上面的 alertMessage.addAction (UIAlertAc 05/03 16:32
vicjoyce0328: tion(title:style: handler: ) ,handler 應該是要寫 05/03 16:32
vicjoyce0328: callActionHandler 而不是nil 05/03 16:32
vicjoyce0328: 沒看完...alertMessage 那段沒錯,上面整個closure 05/03 17:17
farcecat: 謝謝大家的解釋,我懂了 05/04 11:17
lemontea0328: https://goo.gl/rWRtsQ 05/05 09:47
lemontea0328: 之前寫的閉包小練習給你參考 05/05 09:47
farcecat: 謝謝 05/08 11:30
farcecat: 謝謝l大的分享,很清楚~ 05/08 11:30