我已经看到了正常的UIButton:
NSArray *actions = [viewController.addButton actionsForTarget:viewController forControlEvent:UIControlEventTouchUpInside];
XCTAssertTrue([actions containsObject:@”addNumbers:”], @””);
但是现在我想为rightBarButtonItem做同样的事情!我已经测试了VC上存在的这个按钮但是没有接口actionForTargets!
我也尝试了这个,但它不起作用:
NSArray *actions = [self.navigationItem.rightBarButtonItem actionsForTarget:self forControlEvent:UIControlEventTouchUpInside];
或
NSArray *actions = [[self.navigationItem.rightBarButtonItem target] actionsForTarget:self forControlEvent:UIControlEventTouchUpInside];
不是他们的作品。任何人都为UIBarButton编写了测试代码,以检查按钮是否连接到正确的IBAction?
答案 0 :(得分:0)
你可以循环遍历navigationBar的子视图,并找到一个UIControl整个allTargets方法包含rightBarButtonItem。
一旦你有了,你就可以在那个UIControl上调用actionForTarget:forControlEvents:其中rightBarButtonItem是目标,而UIControl的allControlEvents是forControlEvents参数:
//get the underlying control
for(UIControl * control in self.navigationController.navigationBar.subviews)
{
if([control isKindOfClass:UIControl.class])
{
//we found the right one
if([control.allTargets containsObject:self.navigationItem.rightBarButtonItem])
{
NSArray <NSString*> * actions = [control actionsForTarget:self.navigationItem.rightBarButtonItem forControlEvent:[control allControlEvents]];
//do something with actions.firstObject;
return;
}
}
}
但是,我认为UINavigationBar的子视图没有公开定义的布局,所以这是一个脆弱的解决方案。