iOS: Navigation bar with images for buttons

此生再无相见时 提交于 2019-12-18 15:47:44

问题


I would like to create a NavigationBar with images as buttons on the right side of the NavigationBar.

Something like below Snapshot

How can I achieve this?


回答1:


Hope This Helps

viewController.navigationItem.titleView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"yourimage.png"]];
UIBarButtonItem * item = [[UIBarButtonItem alloc] initWithCustomView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"yourimage2.jpg"]]];    
viewController.navigationItem.rightBarButtonItem = item;    



回答2:


Here the Code, Just call below Methods From viewDidLoad method

  - (void)addCustomButtonOnNavBar
  {
   UIBarButtonItem * item1= [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"passImageNmae1"] style:UIBarButtonItemStylePlain target:self action:@selector(yourButtonAction1)];
   UIBarButtonItem * item2= [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"passImageNmae2"] style:UIBarButtonItemStylePlain target:self action:@selector(yourButtonAction2)];
  NSArray * buttonArray =[NSArray arrayWithObjects:item1,item2 ,nil];

   self.navigationItem.rightBarButtonItems =buttonArray;

  }



回答3:


UIView *viewWithButtons = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 44)];
//view customization
UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
//Button customiztaion
[viewWithButtons addSubview:leftButton];
UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
//Button customiztaion
[viewWithButtons addSubview:rightButton];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:viewWithButtons];
[viewWithButtons release];



回答4:


I use a category for this:

UIBarButtonItem+WithImageOnly.h:

#import <UIKit/UIKit.h>

@interface UIBarButtonItem (WithImageOnly)

- (id)initWithImageOnly:(UIImage*)image target:(id)target action:(SEL)action;

@end

UIBarButtonItem+WithImageOnly.m:

#import "UIBarButtonItem+WithImageOnly.h"

@implementation UIBarButtonItem (WithImageOnly)

- (id)initWithImageOnly:(UIImage *)image target:(id)target action:(SEL)action {    
    CGRect frame = CGRectMake(0, 0, image.size.width, image.size.height);
    frame = CGRectInset(frame, -5, 0);

    UIButton *button = [[UIButton alloc] initWithFrame:frame];
    [button setImage:image forState:UIControlStateNormal];
    [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];

    return [self initWithCustomView:button];
}

@end

Usage:

UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithImageOnly:[UIImage imageNamed:@"image"] target:self action:@selector(someAction:)]


来源:https://stackoverflow.com/questions/13122817/ios-navigation-bar-with-images-for-buttons

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