Center elements vertically inside UINavigationBar with custom height

前提是你 提交于 2019-12-04 07:40:11

The cleanest solution I've found to this problem was to use my own subclass of UINavigationBar and center the buttons vertically by overriding the layoutSubviews method:

- (void)layoutSubviews
{
    [super layoutSubviews];

    NSArray *subviews = self.subviews;
    for (UIView *view in subviews) {
        if ([view isKindOfClass:[UIButton class]]) {
            view.frame = ({
                CGRect frame = view.frame;
                CGFloat navigationBarHeight = CGRectGetHeight(self.frame);
                CGFloat buttonHeight = CGRectGetHeight(view.frame);
                frame.origin.y = (navigationBarHeight - buttonHeight) / 2.0f;
                frame;
            });
        }
    }
}

To make a UINavigationController use your subclass of UINavigationBar you can use the initWithNavigationBarClass:toolbarClass: initialiser:

UINavigationController *navigationController = [[UINavigationController alloc] initWithNavigationBarClass:[MyNavigationBar class] toolbarClass:nil];
Renish Dadhaniya

Did you try to add the following code to your viewDidLoad Method :

if ([self respondsToSelector:@selector(edgesForExtendedLayout)])
 self.edgesForExtendedLayout = UIRectEdgeNone;

It is quickly explained in Apple migrating to iOS 7 Documentation : https://developer.apple.com/library/ios/documentation/userexperience/conceptual/TransitionGuide/AppearanceCustomization.html

//it's leave the status-bar height above.

Ajay Sharma

There is a quick crack to this, unless you find the proper solution, this would definitely work ;)

  • Check for system running iOS7.

    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)
    {
       // Add below code
    }
    
  • Add Label to the Navigation Bar :

    UINavigationBar *bar = [self.navigationController navigationBar];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(110, 55, 150, 20)]; //Set the frame appropriate to your screen
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont boldSystemFontOfSize:14];
    label.adjustsFontSizeToFitWidth = NO;
    label.textAlignment = UITextAlignmentCenter;
    label.textColor = [UIColor blackColor];
    label.highlightedTextColor = [UIColor blackColor];
    [bar addSubview:label];
    

Swift 3 version of Tiago his answer

override func layoutSubviews() {
    super.layoutSubviews()

    subviews.filter { (subview) -> Bool in
        return subview is UIButton
    }.forEach { (subview) in
        subview.center.y = frame.height / 2
    }
}

Adjusting the titleView vertical postion

setTitleVerticalPositionAdjustment(-10, for: .default)

You can change size of navigation bar with just changing it's frame:

CGRect navigationBarFrame = self.navigationController.navigationBar.frame;

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!