Custom UINavigationBar with custom height causes the UIBarButtonItem's to be positioned wrong

China☆狼群 提交于 2019-12-20 08:49:48

问题


I created my own subclass of UINavigationBar in order to enable custom background that is taller than 44pxs.

I did it by overriding these two methods:

-(void) drawRect:(CGRect)rect
{
    [self.backgroundImage drawInRect:CGRectMake(0, 0, self.backgroundImage.size.width, self.backgroundImage.size.height)];
}

- (CGSize)sizeThatFits:(CGSize)size 
{
    CGRect frame = [UIScreen mainScreen].applicationFrame;
    CGSize newSize = CGSizeMake(frame.size.width , self.backgroundImage.size.height);
    return newSize;
}

And this is the result:

Now, my problem as you can see is that all the UIBarButtonItem's (and the titleView) are placed at the bottom of the navigation bar.

I would like them to be pinned to the top of the bar (with some padding of course). What to I need to override to achieve that?

Thanks!

EDIT:

This is the solution that I used:

-(void) layoutSubviews
{
    [super layoutSubviews];
    for (UIView *view in self.subviews)
    {
        CGRect frame = view.frame;
        frame.origin.y = 5;
        view.frame = frame;
    }
}

Does the trick for idle state, still have some weird behavior on push and pop items.


回答1:


Try to override layoutSubviews: call [super layoutSubviews] inside and then reposition the items.




回答2:


To solve the push/pop issue use setTitleVerticalPositionAdjustment in sizeThatFits:(CGSize)size

- (CGSize)sizeThatFits:(CGSize)size {
    UIImage *img = [UIImage imageNamed:@"navigation_background.png"];
    [self setTitleVerticalPositionAdjustment:-7 forBarMetrics:UIBarMetricsDefault];
    CGRect frame = [UIScreen mainScreen].applicationFrame;
    CGSize newSize = CGSizeMake(frame.size.width , img.size.height);
    return newSize;
}


来源:https://stackoverflow.com/questions/8726006/custom-uinavigationbar-with-custom-height-causes-the-uibarbuttonitems-to-be-pos

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