如何为backButton实施longPressed操作

如何为backButton实施longPressed操作

本文介绍了iOS/Swift:如何为backButton实施longPressed操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在尝试为我的应用中的每个ViewController实施自定义后退按钮.我希望它有两个动作.如果该按钮被点击,则它应能正常工作并向上导航.如果按下按钮的时间更长,则应转到预定义的ViewController.

I'm trying to implement a custom back button for every ViewController in my app. I want it to have two actions. If the button gets tapped, it should behave normally and go up the navigation stack. If the button gets pressed longer it should go to a predefined ViewController.

如何仅快速地为后退按钮实现这一目标?

How can I achieve this for only the backbutton in swift?

推荐答案

您可以隐藏默认的导航后退按钮,并通过以下方式添加自定义按钮:

You can hide your default navigation back button and add a custom button this way:

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")
    }

}

这篇关于iOS/Swift:如何为backButton实施longPressed操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 18:56