swift UI專項訓練42 用Swift代碼實現頁面跳轉與傳值,uiswift
之前我們做過如果要點擊一個按鈕實現跳轉到另一個按鈕的辦法,有時候我們需要通過一些動作來觸發頁面的跳轉,比如搖動手機,這樣就不能直接用連線的辦法來實現跳轉了,那麼如何通過代碼的方式來實現跳轉呢?依舊使用過渡的方法,在storyboard中把要實現跳轉的兩張頁面連線,注意不再局限於按鈕等確定的實體和另一張頁面連線,只要跳轉關係是從一張到另一張,把兩張頁面連起來即可,連線選擇show,這裡就不示範了,注意一定要給這個seuge取一個名字,因為後面要遇到,這裡取名showDetail
。比如我現在需要通過搖動手機來實現跳轉,在第一張頁面中重寫以下方法:
override func shouldPerformSegueWithIdentifier(identifier: String?, sender: AnyObject?) -> Bool { if self.showArray.count != 0 && self.markpoint != 0//你自己的判斷條件 { return true } else { return false } }
上面這個方法來判斷是否可以進行頁面跳轉,在其中加入我們自己的判斷條件。
然後在捕獲搖動手機動作的方法中(如果不懂這個捕獲的代碼,可以看我前面寫的文章,有介紹)加入我們的判斷跳轉條件,如果為真實現跳轉,如果不滿足跳轉條件,給出你自己的警告:
override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent) { if motion == UIEventSubtype.MotionShake { if markpoint == 1 && self.searchpoint == false{ //不能跳轉,給出警告 var alertController1 = UIAlertController(title: "沒有合格菜品!", message: nil, preferredStyle: .Alert) var cancelAction = UIAlertAction(title: "返回", style: .Cancel, handler: nil) alertController1.addAction(cancelAction) self.presentViewController(alertController1, animated: true, completion: nil) } if self.searchpoint == true{ //可以跳轉 self.performSegueWithIdentifier("showDetail", sender: self)//跳轉到下一個頁面,識別“showDetail” } } }
實現跳轉主要使用了performSegueWithIdentifier方法。如果要傳輸局,使用方法prepareForSegue,My Code如下:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetail" { let destinationController = segue.destinationViewController as ShowTableViewController destinationController.navigationItem.title = "搖到的菜" destinationController.tempCaipin = self.showArray //傳值 } }
第一個頁面:
搖動手機後跳轉: