我有三个 View Controller ,在导航栏的左右两侧各有两个按钮,如下图所示。
我以编程方式创建这些按钮,而不是在每个相应的 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
。
输出:
更新:
如果你想在没有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/