如何手动触发UIBarButtonItem点击事件?

问题描述 投票:1回答:2

我有一个自定义UIButton,它是UIBarButtonItem的子视图:

guard let tab1 = self.tabBar.items![0].value(forKey: "view") as? UIView else {return}

    let button2Test = UIButton()
    tab1.addSubview(button2Test)

自定义UIButton,有一个目标:

button2Test.addTarget(self, action: #selector(buttonTouchUpInsideP3), for: [.touchUpInside])
button2Test.addTarget(self, action: #selector(buttonTouchInsideBoundsP3), for: [.touchDown, .touchDragEnter])
button2Test.addTarget(self, action: #selector(buttonDraggedOutOfBoundsP3), for: [.touchDragExit, .touchCancel])

基本上,在buttonTouchUpInsideP3函数中,我想以编程方式/手动使UIBarButtonItem处于特定索引好像被轻击时触发,因为UIButton的目标不允许下面的实际UIBarButtonItem被窃听,很不幸...

我因错误而失败的尝试是:(我从outdated Q获得)。请注意,我在buttonTouchUpInsideP3目标函数中调用了该函数,放开按钮后即调用该函数。

let homeTabBarItem = self.tabBar.items![0]
UIApplication.sharedApplication.sendAction(homeTabBarItem.action, to: homeTabBarItem.target, from: nil, forEvent: nil)
ios swift uibutton uibarbuttonitem uitabbar
2个回答
0
投票

您可以直接设置UIBarButtonItem的target和action属性。


0
投票

我想出了办法:

tabBarController.selectedIndex = 0

只需将其放在buttonTouchUpInside函数中! ;)

您可能还应该打电话:

self.tabBar(self.tabBar, didSelect: self.tabBar.items![0])
© www.soinside.com 2019 - 2024. All rights reserved.