ios - 以编程方式从 UIBarButtonItem 继续

标签 ios swift segue selector uibarbuttonitem

我有三个 View Controller ,在导航栏的左右两侧各有两个按钮,如下图所示。

Example VC

我以编程方式创建这些按钮,而不是在每个相应的 View Controller (VC) 中编写代码,我决定编写一个 Helper 类来创建按钮。

// Note: I am using FontAwesome as a third-party library.

class Helper: NSObject {

    static func loadNavBarItems(vc: UIViewController) {
        let profileButton = UIBarButtonItem()
        let addButton = UIBarButtonItem()

        let attributes = [NSFontAttributeName: UIFont.fontAwesome(ofSize: 20)] as [String: Any]

        profileButton.setTitleTextAttributes(attributes, for: .normal)
        addButton.setTitleTextAttributes(attributes, for: .normal)

        profileButton.title = String.fontAwesomeIcon(name: .userCircle)
        addButton.title = String.fontAwesomeIcon(name: .plus)

        vc.navigationItem.leftBarButtonItem = profileButton
        vc.navigationItem.rightBarButtonItem = addButton
    }

    func segueToProfile(vc: UIViewController) { // I need help here. }

}

然后我从每个 VC 的 viewDidLoad() 调用 Helper.loadNavBarItems(vc: self)

我现在要做的是在按下其中一个按钮时触发 segue(假设它是配置文件按钮)。所以,我需要定义 profile.action。因此,在 Helper 类中,我必须编写一个函数 segueToProfile,它采用 View Controller (vc) 并运行 performSegueWithIdentifier

问题是,我不完全理解如何通过选择器传递不同类型的参数,我可能不擅长谷歌搜索,但我找不到任何足够接近我的问题让我理解如何实现这个。

非常感谢您的帮助。

供引用,this is the structure of my Storyboard .

编辑:如 Storyboard结构屏幕截图所示,我已经创建了从三个 View Controller 到目标 View Controller 的转接。

最佳答案

创建 barButtonItem:

navigationItem.rightBarButtonItem = UIBarButtonItem(title: "😱", style: .plain, target: self, action: #selector(ProfileButtonTapped))

为 barButtonItem 创建 action 和 segue:

 func ProfileButtonTapped() { 
    print("Button Tapped")   
    performSegue(withIdentifier: "YourSegueIdentifierName", sender: self) 
    //If you want pass data while segue you can use prepare segue method
   }

注意:执行segue,您必须从 Storyboard中提供segue identifier name

enter image description here

输出:

enter image description here

更新:

如果你想在没有segue的情况下连接你的destVC,你可以使用下面的方法:

注意:要使用下面的方法,您必须在 identity inspector 中设置 storyBoard Id

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let DestVC = storyboard.instantiateViewController(withIdentifier: "DestVcName") as! DestVcName //UINavigationController
self.present(DestVC, animated: true, completion: nil)

关于ios - 以编程方式从 UIBarButtonItem 继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40891119/

相关文章:

ios - 无法使用 unity ios 将文件保存到 AppGroup 的共享容器

ios - 在 View Controller 之间共享一个例程

ios - 如何访问位于容器 subview 中的 UITextFiled 的 UITextFieldDelegate 方法?

swift - CoreData - PickerView 更新 tableView

ios - 准备Segue Swift

ios - 未调用编程式 UIButton 操作

swift - 无法在 Swift 中实现这种设计模式?

swift - 提示用户 Siri 应用程序支持权限(付款意向扩展)

swift - 完成处理程序后执行Segue

ios - Firebase - 将唯一 ID 保存在类变量中并将其数据发送到另一个 Controller - Swift