问题
I want to perform segue when I click on Back button. For it I do:
override func didMoveToParentViewController(parent: UIViewController?) {
self.performSegueWithIdentifier("fromGalleryToBody", sender: self)
}
but it crashes my app when I tap on Back button. How can I realize it?
回答1:
Default button of navigation gives you functionality to move to the previous view
You can check it by :
override func didMoveToParentViewController(parent: UIViewController?) {
if parent == nil {
println("Back Pressed")
}
}
But the situation is didMoveToParentViewController
means it already move to the previous view.
You can add custom button as back button in your navigation bar. Then your issue will be solved.
Add button Programmatically :
let backButton = UIBarButtonItem(title: "Назад в будущее", style: .Plain, target: self, action: "toMainFromGallery")
self.navigationItem.leftBarButtonItem = backButton
Function :
func toMainFromGallery {
}
Button With Back Icon :
var backButton = UIButton(frame: CGRectMake(0, 0, 70.0, 70.0))
var backImage = UIImage(named: "backBtn")
backButton.setImage(backImage, forState: UIControlState.Normal)
backButton.titleEdgeInsets = UIEdgeInsetsMake(10.0, 10.0, 10.0, 0.0)
backButton.setTitle("Back", forState: UIControlState.Normal)
backButton.addTarget(self, action: "buttonPressed", forControlEvents: UIControlEvents.TouchUpInside)
var backBarButton = UIBarButtonItem(customView: backButton)
self.navigationItem.leftBarButtonItem = backBarButton
There should be space between left If you want to remove it add spacer like as :
var spacer = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FixedSpace, target: nil, action: nil)
spacer.width = -15
self.navigationItem.leftBarButtonItems = [spacer,backBarButton]
Back Icon Image should be in 22px, 44px and 66px = @1x , @2x and 3x respectivaly
回答2:
please check. here is the example which you need .
Delegates and Segues in Swift or
you need to set like this in you view controller as andrew said .
Put this code inside the View Controller you want to trap the Back button call from:
override func didMoveToParentViewController(parent: UIViewController?) {
if (!(parent?.isEqual(self.parentViewController) ?? false)) {
println("Back Button Pressed!")
}
}
Inside of the if block, handle whatever you need to pass back. You'll also need to have a reference back to calling view controller as at this point most likely both parent and self.parentViewController are nil, so you can't navigate the View Controller tree.
Also, you might be able to get away with simply checking parent for nil as I haven't found a case where pressing the back button didn't result in parent being nil. So something like this is a bit more concise:
override func didMoveToParentViewController(parent: UIViewController?) {
if (parent == nil) {
println("Back Button Pressed!")
}
}
for more detail please refer this answer Segue on Backbutton
来源:https://stackoverflow.com/questions/31717315/perform-segue-on-press-on-back-button