【问题标题】:Adjust the BarButtonItem position in UINavigationBar调整 UINavigationBar 中 BarButtonItem 的位置
【发布时间】:2013-11-15 07:38:31
【问题描述】:

我需要在 UINavigationBar 中调整 UIBarButtonItem 的垂直位置。我认为有办法做到这一点。将 UIView 添加到 UIBarButtonItem 并将 UIButton 添加到 UIView。如果你只有一两个导航栏也没关系。但是我认为如果你有几十个 UINavigationBar 尤其是在故事板中,这有点太麻烦了。所以我做了一些研究并找到了一个简单的解决方案。也就是使用类别。这是我的源代码:

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation"

-(void)viewWillAppear:(BOOL)animated
{
    [self show:NO];
}

// do your override
-(void)viewWillLayoutSubviews
{
    [self changeTheButtonPosition:self.navigationItem.leftBarButtonItem];
    [self changeTheButtonPosition:self.navigationItem.rightBarButtonItem];
}

-(void)viewDidAppear:(BOOL)animated
{
    [self show:YES];
}

#pragma clang diagnostic pop

-(void)show:(BOOL)show
{
    self.navigationItem.leftBarButtonItem.customView.hidden = !show;
    self.navigationItem.rightBarButtonItem.customView.hidden = !show;
}

- (void)changeTheButtonPosition:(UIBarButtonItem *)barButtonItem
{
    if ( barButtonItem )
    {
        UIView* customView = barButtonItem.customView;
        //        NSLog(@"custom view frame = %@",NSStringFromCGRect(customView.frame));
        CGRect frame = customView.frame;
        CGFloat y = SYSTEM_VERSION_LESS_THAN(@"7") ? 10.0f : 5.0f;
        customView.frame = CGRectMake(frame.origin.x, y, frame.size.width, frame.size.height);
    }
}

它在 iOS 7 和 iOS 6 的第一个视图控制器中完美运行。但它不适用于 iOS 6 中的推送 UIViewController。我找不到任何原因。有人可以建议吗?我在 iOS 6 中的代码有什么问题?

【问题讨论】:

标签: ios layout uinavigationbar uinavigationitem


【解决方案1】:

您应该能够使用 iOS5 中引入的UIAppearance 代理方法来实现此目的。特别是:

- (void)setBackgroundVerticalPositionAdjustment:(CGFloat)adjustment forBarMetrics:(UIBarMetrics)barMetrics
- (void)setTitlePositionAdjustment:(UIOffset)adjustment forBarMetrics:(UIBarMetrics)barMetrics

查看UIBarButtonItem docs 了解更多信息。

【讨论】:

  • 然而,这在 iOS 7 中似乎不太好用。在那里设置标题位置时我遇到了一些问题,然后操作系统接管并且对任何其他内容的任何其他调整都会导致按钮移动。任何方向都会移动它。最终目的地是默认位置。具体来说,我有一个编辑按钮的问题,并试图将其固定到更高的导航栏的顶部。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多