Customize navigation bar with title view

前端 未结 8 2320
一生所求
一生所求 2020-12-08 13:41

I am trying to add a custom view in the center of a navigation bar and I am using the following code to test it:

UIView * testView = [[UIView alloc] init];
[         


        
8条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-08 14:02

    #import  
    @interface MasterViewController : UITableViewController
    @end
    
    
    #import "MasterViewController.h"
    @interface MasterViewController ()
    @end
    
    @implementation MasterViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
    
        self.navigationItem.titleView = [self titleView];
    }
    
    - (UIView *)titleView {
        CGFloat navBarHeight = self.navigationController.navigationBar.frame.size.height;
        CGFloat width = 0.95 * self.view.frame.size.width;
        UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, navBarHeight)];
    
        UIImage *logo = [UIImage imageNamed:@"logo.png"];
        UIButton *logoButton = [UIButton buttonWithType:UIButtonTypeCustom];
        CGFloat logoY = floorf((navBarHeight - logo.size.height) / 2.0f);
        [logoButton setFrame:CGRectMake(0, logoY, logo.size.width, logo.size.height)];
        [logoButton setImage:logo forState:UIControlStateNormal];
    
        UIImage *bubble = [UIImage imageNamed:@"notification-bubble-empty.png"];
        UIImageView *bubbleView = [[UIImageView alloc] initWithImage:bubble];
    
        const CGFloat Padding = 5.0f;
        CGFloat bubbleX = 
            logoButton.frame.size.width + 
            logoButton.frame.origin.x + 
            Padding;
        CGFloat bubbleY = floorf((navBarHeight - bubble.size.height) / 2.0f);
        CGRect bubbleRect = bubbleView.frame;
        bubbleRect.origin.x = bubbleX;
        bubbleRect.origin.y = bubbleY;
        bubbleView.frame = bubbleRect;
    
        [containerView addSubview:logoButton];
        [containerView addSubview:bubbleView];
    
        return containerView;
    }
    
    @end
    

提交回复
热议问题