我已经创建了一个没有UITabBarController的UITabBar和UITabBarItems,现在我想知道如何在点击UITabBarItem时放置一个动作。我应该用什么方法对UITabBarItem采取行动?
You can't set an action on a UITabBarItem
object directly. Instead, your view controller should implement the following UITabBarDelegate
method:
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item;
This method is called when the user selects a tab (ie UITabBarItem
).
Are you using a UINavigationController? If so, from the active view controller subclass you get the navigationItem and add the buttons to it, eg:
- (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? 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:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.