codeiOS专题资源__系统知识点iOS -- Demo

UINavigationBar属性及返回按钮更改小结

2015-07-24  本文已影响29158人  tripleCC

有时候这些属性搞得蛮乱的,记录下以便查阅

UINavigationBar属性

[UINavigationBar appearanceWhenContainedIn:self, nil];


- 背景图片
- ![](http:https://img.haomeiwen.com/i608238/72847773e7f3af76.png?imageMogr2/auto-orient/strip|imageView2/2/w/1240)

```objc
// barMetrics需要设置成UIBarMetricsDefault
- (void)setBackgroundImage:(UIImage *)backgroundImage forBarMetrics:(UIBarMetrics)barMetrics

@property(nonatomic,retain) UIImage *backIndicatorTransitionMaskImage;

- 标题垂直偏移
- ![](http:https://img.haomeiwen.com/i608238/7761bd834709f62d.png?imageMogr2/auto-orient/strip|imageView2/2/w/1240)

```objc
- (void)setTitleVerticalPositionAdjustment:(CGFloat)adjustment forBarMetrics:(UIBarMetrics)barMetrics

返回按钮更改

系统原装效果:


如果有以下需求:

分析
解决

综合以上说明,这里给出三种方式(都是针对的自定义UINavigationController):

  - (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    viewController.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:nil action:nil];

    [super pushViewController:viewController animated:animated];
}
  // 获取特定类的所有导航条
  UINavigationBar *navigationBar = [UINavigationBar appearanceWhenContainedIn:self, nil];
  
  // 方式1:使用自己的图片替换原来的返回图片
  navigationBar.backIndicatorImage = [UIImage imageNamed:@"NavBack"];
  navigationBar.backIndicatorTransitionMaskImage = [UIImage imageNamed:@"NavBack"];

  // 方式2:设置返回图片颜色
  navigationBar.tintColor = [UIColor whiteColor];
[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -100) forBarMetrics:UIBarMetricsDefault];
    - (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    if (self.viewControllers.count != 0) {
        viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"NavBack"] style:UIBarButtonItemStyleDone target:self action:@selector(back)];
    }

    [super pushViewController:viewController animated:animated];
}
    - (void)back
    {
    [self popViewControllerAnimated:YES];
    }
方案对比


通过以下方式可以使按钮向左边靠:

...
// 返回按钮内容左靠
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;

// 让返回按钮内容继续向左边偏移10
button.contentEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
...
viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
上一篇下一篇

猜你喜欢

热点阅读