我也需要这个,搜索了一下,最终在 UITabBarController 上构建了以下类别。
让操作表出现在当前选项卡上的技巧是您永远不想实际访问该操作表呈现选项卡。使用启动操作表的 UIButton 覆盖该位置的选项卡栏。
像往常一样在情节提要中绘制标签栏,在发生特殊行为的位置留下一个空栏项目。然后添加这个类别...
// UITabBarController+Button.h
@interface UITabBarController (Button) <UIActionSheetDelegate>
- (void)replaceItemAtIndex:(NSUInteger)index withButtonImage:(UIImage*)buttonImage;
@end
// UITabBarController+Button.m
#import "UITabBarController+Button.h"
#define kBUTTON_TAG 4096
@implementation UITabBarController (Button)
- (void)replaceItemAtIndex:(NSUInteger)index withButtonImage:(UIImage*)buttonImage {
UIButton *button = (UIButton *)[self.view viewWithTag:kBUTTON_TAG];
if (!button) {
button = [UIButton buttonWithType:UIButtonTypeCustom];
button.tag = kBUTTON_TAG;
[button setBackgroundImage:buttonImage forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
UITabBar *bar = self.tabBar;
CGFloat width = bar.frame.size.width / bar.items.count;
button.frame = CGRectMake(index*width, bar.frame.origin.y, width, bar.frame.size.height);
[self.view addSubview:button];
}
}
#pragma mark - Handle button tap
- (void)buttonTapped:(id)sender {
UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"Action Sheet:"
delegate:self
cancelButtonTitle:@"Cancel"
destructiveButtonTitle:nil
otherButtonTitles:@"Action A", @"Action B", @"Action C", nil];
[sheet showFromTabBar:self.tabBar];
}
使用 index < tabBar.items.count 和按钮的图像调用它。如果是你应用的根vc,你可以这样调用它:
#import "the category i suggest above"
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// whatever else you do in here, then
NSLog(@"%@", self.window.rootViewController); // make sure this is a UITabBarController
// if it is, then ...
UITabBarController *tbc = (UITabBarController *)self.window.rootViewController;
[tbc replaceItemAtIndex:2 withButtonImage:[UIImage imageNamed:@"some image name"]];
return YES;
}