简体   繁体   English

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

[英]How to fire a UIBarButtonItem tap event manually?

I have a situation where I have a custom UIButton that is a subview of a UIBarButtonItem:我有一个自定义 UIButton 的情况,它是 UIBarButtonItem 的子视图:

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

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

The custom UIButton, has a target:自定义 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])

Basically, in the buttonTouchUpInsideP3 function, I want to programmatically / manually make the UIBarButtonItem at a specific index to fire as if it was tapped on , since the target of the UIButton does not allow the actual UIBarButtonItem underneath to be tapped, unfortunately...基本上,在 buttonTouchUpInsideP3 function 中,我想以编程方式/手动使特定索引处的 UIBarButtonItem像被点击一样触发,因为 UIButton 的目标不允许点击下面的实际 UIBarButtonItem,不幸的是......

My attempt which did not work because of errors is: (which I got from an outdated Q ).由于错误而没有成功的尝试是:(我从过时的 Q中得到)。 Note that I call this in the buttonTouchUpInsideP3 target function which ones once you've let go of the button.请注意,我在 buttonTouchUpInsideP3 目标 function 中调用它,一旦你让按钮的 go 出现。

let homeTabBarItem = self.tabBar.items![0]
UIApplication.sharedApplication.sendAction(homeTabBarItem.action, to: homeTabBarItem.target, from: nil, forEvent: nil)

You can just set the UIBarButtonItem's target and action properties directly.您可以直接设置 UIBarButtonItem 的目标和操作属性。

I figured out how to do it:我想出了如何做到这一点:

tabBarController.selectedIndex = 0

Just put this in the buttonTouchUpInside function;只要把这个放在按钮TouchUp里面function; ;) ;)

You should probably also call:您可能还应该致电:

self.tabBar(self.tabBar, didSelect: self.tabBar.items![0])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM