Change position of UIBarButtonItem in UINavigationBar

后端 未结 20 1547
一个人的身影
一个人的身影 2020-11-27 10:31

How can I change the position of a UIBarButtonItem in a UINavigationBar? I would like my button to be about 5px higher than its normal position.

20条回答
  •  清歌不尽
    2020-11-27 10:56

    The best solution I could find is to initialize a UIBarButtonItem with a subview that includes extra space to the left/right. That way you wont have to worry about subclassing, and changing the layout of other elements inside the navigation bar, such as the title.

    For example, to move a button 14 points to the left:

    UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, image.size.width + 14, image.size.height)];
    UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(-14, 0, image.size.width, image.size.height);
    [button setImage:image forState:UIControlStateNormal];
    [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    [containerView addSubview:button];
    
    UIButton* button2 = [UIButton buttonWithType:UIButtonTypeCustom];
    button2.frame = CGRectMake(0, 0, image.size.width + 14, image.size.height);
    [button2 addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    [containerView addSubview:button2];
    
    UIBarButtonItem* item = [[[self alloc] initWithCustomView:containerView] autorelease];
    

提交回复
热议问题