[英]How to create an action for a UITabBarItem?
我已经创建了一个没有UITabBarController的UITabBar和UITabBarItems,现在我想知道如何在点击UITabBarItem时放置一个动作。我应该用什么方法对UITabBarItem采取行动?
You can't set an action on a UITabBarItem
object directly. 您无法直接在
UITabBarItem
对象上设置操作。 Instead, your view controller should implement the following UITabBarDelegate
method: 相反,您的视图控制器应实现以下
UITabBarDelegate
方法:
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item;
This method is called when the user selects a tab (ie UITabBarItem
). 当用户选择选项卡(即
UITabBarItem
)时,将调用此方法。
Are you using a UINavigationController? 你在使用UINavigationController吗? If so, from the active view controller subclass you get the navigationItem and add the buttons to it, eg:
如果是这样,从活动视图控制器子类获取navigationItem并向其添加按钮,例如:
- (void) viewWillAppear:(BOOL)animated;
{
[super viewWillAppear: animated];
UIBarButtonItem * leftButtonItem = [[[UIBarButtonItem alloc] initWithTitle: @"Don't Show Again" style: UIBarButtonItemStyleBordered target: self action: @selector(permanentlyCloseWelcomeView)] autorelease];
[[self navigationItem] setLeftBarButtonItem: leftButtonItem];
}
Can you get away with using instances of UIToolbar and UIBarButtonItem instead? 您是否可以使用UIToolbar和UIBarButtonItem的实例? It could be more straightforward.
它可能更直截了当。
toolBar = [[UIToolbar alloc] init];
newPlayerItem = [[UIBarButtonItem alloc] initWithTitle:@"+"
style:UIBarButtonItemStyleBordered
target:self
action:@selector(newPlayer:)];
NSArray *toolBarItemsArray = [[NSArray alloc] initWithObjects:newPlayerItem, nil];
[toolBar setItems:toolBarItemsArray];
[toolBarItemsArray release];
There is a better method than didSelectItem: for each TabBarItem you create an action: 有一个比didSelectItem更好的方法:对于每个TabBarItem,你创建一个动作:
and then you can use the new actions:
[item1 setAction:@selector(pressItem1:)];
[item2 setAction:@selector(pressItem2:)];
[item3 setAction:@selector(pressItem3:)];
[item4 setAction:@selector(pressItem4:)]; 然后你可以使用新的动作:
-(void)pressItem1:(UITabBarItem *) item1 {<br/>
// Here comes your code which<br/>
// occurs after pressing item1.<br/>
}
That works for me 这对我行得通
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.