UITabBar宽度不随屏幕尺寸

时间:2015-10-23 10:14:32

标签: ios objective-c autolayout uitabbar uitabbaritem

我正在另一个UITabBar内实施UITabBar。我的问题是,无论屏幕大小如何,第二个TabBar宽度保持不变。这在更大的屏幕中脱颖而出。我附上了一个截图,让你更了解。使用蓝色背景指示选择 First TabBar on Top Second on the bottom

Second Tab in Second TabBar Selected

Third tab Selected in Second TabBar Controller

以下是代码:

GRect rect = CGRectMake(0, 0, self.tabBar.frame.size.width/2, self.tabBar.frame.size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context,
                                   [[UIColor colorWithRed:102.0/255.0 green:197.0/255.0 blue:234.0/255.0 alpha:1.0] CGColor]);

    CGContextFillRect(context, rect);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    self.tabBar.selectionIndicatorImage = img;

iPhone6 Plus的截图

Second Tab Of First TabBar selected(not part of the question, just to show the full picture)

1 个答案:

答案 0 :(得分:5)

感谢您提供突出显示按钮的片段。
你想要这样的东西吗?
纵向:

enter image description here


横向:

enter image description here

我的ViewController代码:

#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITabBar *tabBar;
@property (weak, nonatomic) IBOutlet UITabBar *topTabBar;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [[UITabBar appearance] setTintColor:[UIColor redColor]];
    [[UITabBarItem appearance] setTitleTextAttributes:@{NSFontAttributeName :  [UIFont boldSystemFontOfSize:20]} forState:UIControlStateNormal];
}

- (void)viewDidLayoutSubviews {

    [self highlightTabBarItems:self.tabBar];
    [self highlightTabBarItems:self.topTabBar];
}

- (void)highlightTabBarItems:(UITabBar*)currentTabBar {

    CGFloat highlightedWidth = self.view.frame.size.width/currentTabBar.items.count;
    [currentTabBar setItemWidth:highlightedWidth];
    CGRect rect = CGRectMake(0, 0, highlightedWidth, currentTabBar.frame.size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [[UIColor colorWithRed:102.0/255.0 green:197.0/255.0 blue:234.0/255.0 alpha:1.0] CGColor]);
    CGContextFillRect(context, rect);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    currentTabBar.selectionIndicatorImage = img;
}

@end