Add segmented control to navigation bar and keep title with buttons

后端 未结 8 2586
借酒劲吻你
借酒劲吻你 2020-12-04 10:03

I want to add segmented control to the navigation bar but also keep the title and buttons, like in iOS 7 Appstore purchased section (example)

I have tried adding seg

8条回答
  •  南方客
    南方客 (楼主)
    2020-12-04 10:39

    I found two solutions:

    1) As suggested by neural5torm, you can add the segmented control to an UIView with the same background color of the navigation bar

    You can remove UINavigationBar's hairline in this way:

    for (UIView *view in self.navigationController.navigationBar.subviews)
    {
        for (UIView *view2 in view.subviews)
        {
            if ([view2 isKindOfClass:[UIImageView class]])
            {
                [view2 removeFromSuperview];
            }
        }
    }
    

    This is ok for not translucent navigation bar.



    If you want a translucent navigation bar:
    2) Subclass UINavigationBar to create a taller bar by overriding sizeThatFits

    - (CGSize)sizeThatFits:(CGSize)size
    {
        size.width = self.frame.size.width;
        size.height = your height (probably 88.0f);
        return size;
    }
    


    To use your custom navigation bar:

    UINavigationController *navController = [[UINavigationController alloc] initWithNavigationBarClass:[YouNavigationBar class] toolbarClass:nil];
    [navController setViewControllers:@[viewController]];
    


    Title and button items will be at the bottom. Adjust their vertical positions (in the init of your custom navigation bar or via appearance proxy)

    // Title view
    [self setTitleVerticalPositionAdjustment:-dy forBarMetrics:UIBarMetricsDefault];
    
    // Button item as icon/image 
    [[UIBarButtonItem appearanceWhenContainedIn:[YourCustomNavigationBar class], nil] setBackgroundVerticalPositionAdjustment:-dy forBarMetrics:UIBarMetricsDefault];
    

    Look at the UIBarButtonItem class reference, there are also setTitlePositionAdjustment and other methods for back button


    When you create your segmented control, add it to the navigation bar

    [self.navigationController.navigationBar addSubview:segmentedControl];
    


    The segmented control will be at the top. Adjust its vertical position by overriding didAddSubview in your custom navigation bar

    - (void)didAddSubview:(UIView *)subview
    {
        [super didAddSubview:subview];
    
        if ([subview isKindOfClass:[UISegmentedControl class]])
        {
            CGRect frame = subview.frame;
            frame.origin.y += your extra height (probably 44.0f);
            subview.frame = frame;
        }
    }
    

提交回复
热议问题