TabBar选择指示器图像未在Objective C中获取tabBar高度的整个大小

时间:2014-10-31 13:28:39

标签: ios objective-c uitabbar uitabbaritem

我正在更改setSelectionIndicatorImage,当我在iOS 8上运行应用时,我会在图片和tabBar的常规宽度之间找到间距。有没有办法可以将标签栏的高度与setSelectionIndicatorImage匹配?此外,我在第一个标签的左侧和最后一个标签的右侧获得了几个像素的边距,当选择标签时我也需要用图像覆盖它。

2 个答案:

答案 0 :(得分:2)

在didFinishLaunchingWithOptions上放了这段代码:

UITabBarController *tabBarContr = (UITabBarController *)self.window.rootViewController;

CGFloat tabBarItemWidth = self.window.rootViewController.view.bounds.size.width / tabBarContr.tabBar.items.count;
CGFloat tabBarItemHeight = CGRectGetHeight(tabBarContr.tabBar.frame);

UIView *selectedBottomView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tabBarItemWidth, tabBarItemHeight)];

 CAGradientLayer *gradient = [CAGradientLayer layer];

gradient.colors = [NSArray arrayWithObjects:
                   (id)[UIColor blueButton].CGColor,
                   (id)[UIColor colorWithRed:0.08 green:0.54 blue:1 alpha:1].CGColor,
                   nil];

gradient.frame = selectedBottomView.bounds;

[selectedBottomView.layer insertSublayer:gradient atIndex:0];

UIGraphicsBeginImageContext(selectedBottomView.bounds.size);
[selectedBottomView.layer renderInContext:UIGraphicsGetCurrentContext()];

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

tabBarContr.tabBar.selectionIndicatorImage = image;
tabBarContr.tabBar.translucent = YES;
tabBarContr.tabBar.tintColor = [UIColor whiteColor];

注意:采用imageview而不是渐变

答案 1 :(得分:0)

这可以帮助您根据需要自定义指标图像。您只需在界面构建器

中将Tab Bar类设置为此类
class MyCustomTabBar: UITabBar
{
    var didInit = false
    override func layoutSubviews()
    {
        super.layoutSubviews()

        if didInit == false
        {
            didInit = true
            for subview in subviews {
                // can't hookup to subviews, so do layer.sublayers
                subview.layer.addObserver(self, forKeyPath: "sublayers", options: .New, context: nil)
            }
        }
    }

    deinit
    {
        for subview in subviews
        {
            subview.layer.removeObserver(self, forKeyPath: "sublayers")
        }
    }

    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>)
    {
        // layer.delegate is usually the parent view
        if let l = object as? CALayer, tbButton = l.delegate as? UIView where tbButton.window != nil
        {
            for v in tbButton.subviews
            {
                if String(v.dynamicType) == "UITabBarSelectionIndicatorView" {
                    // do whatever needed with v, this is your indicator view
                }
            }
        }
    }
}