我正在更改setSelectionIndicatorImage
,当我在iOS 8上运行应用程序时,我会得到图像和tabBar
的规则宽度之间的间距。有没有一种方法可以将选项卡栏的高度与setSelectionIndicatorImage
相匹配?此外,我在第一个选项卡的左侧和最后一个选项卡的右侧得到了几个像素的边距,当选择选项卡时,我也需要用图像来覆盖它。
在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];
注意:使用图像视图而不是梯度
这将帮助您根据需要自定义指示器图像。您只需在界面生成器中将选项卡栏的类设置为此类
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
}
}
}
}
}