我正在尝试为我的应用中的每个ViewController实现自定义后退按钮。我希望它有两个动作。如果按钮点击,它应该正常运行并向上导航堆栈。如果按钮按下更长,它应该转到预定义的ViewController。
我怎样才能在swift中只为后退按钮实现这一点?
答案 0 :(得分:3)
您可以隐藏默认导航后退按钮并以这种方式添加自定义按钮:
import UIKit
class SViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//hide your default back button
navigationController!.setNavigationBarHidden(false, animated:true)
//create a new button
var myBackButton:UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
myBackButton.addTarget(self, action: "popToRoot:", forControlEvents: UIControlEvents.TouchUpInside)
myBackButton.setTitle("Back", forState: UIControlState.Normal)
myBackButton.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
myBackButton.sizeToFit()
//create a LongPressGestureRecognizer
var longPressGesture = UILongPressGestureRecognizer(target: self, action: "longPressAction:")
//add LongPressGestureRecognizer into button
myBackButton.addGestureRecognizer(longPressGesture)
var myCustomBackButtonItem:UIBarButtonItem = UIBarButtonItem(customView: myBackButton)
self.navigationItem.leftBarButtonItem = myCustomBackButtonItem
}
//this method will call when you tap on button.
func popToRoot(sender:UIBarButtonItem){
self.navigationController!.popToRootViewControllerAnimated(true)
}
//this method will call when you long press on button
func longPressAction(gestureRecognizer:UIGestureRecognizer) {
//initiate your specific viewController here.
println("Long press detected")
}
}