IOS_自定义navigationBar上的按钮

效果类似这样:




在NavigationBar上增加多个按钮,有以下三种方法。

方法1:

UIView *parentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, myWidth, myHeight)];
[parentView addSubview:customView1];
[parentView addSubview:customView2];

UIBarButtonItem *customBarButtomItem = [[UIBarButtonItem alloc] initWithCustomView:parentView];
self.navigationItem.rightBarButtonItem = customBarButtomItem;


方法2:【这种是本人最常用的】

UIBarButtonItem *myAddButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(myAddAction:)];
UIBarButtonItem *myCoolButton = [[UIBarButtonItem alloc] initWithTitle:@"Cool!" style:UIBarButtonItemStyleDone target:self action:@selector(myCoolAction:)];
NSArray *myButtonArray = [[NSArray alloc] initWithObjects:myCoolButton, myAddButton, nil];
self.navigationItem.rightBarButtonItems = myButtonArray;

方法3:这种太复杂,看看就得了

UIToolbar *tools = [[UIToolbar alloc]
                    initWithFrame:CGRectMake(0.0f, 0.0f, 103.0f, 44.01f)]; // 44.01 shifts it up 1px for some reason
tools.clearsContextBeforeDrawing = NO;
tools.clipsToBounds = NO;
tools.tintColor = [UIColor colorWithWhite:0.305f alpha:0.0f]; // closest I could get by eye to black, translucent style.
                                                              // anyone know how to get it perfect?
tools.barStyle = -1; // clear background
NSMutableArray *buttons = [[NSMutableArray alloc] initWithCapacity:3];

// Create a standard refresh button.
UIBarButtonItem *bi = [[UIBarButtonItem alloc]
    initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refresh:)];
[buttons addObject:bi];
[bi release];

// Create a spacer.
bi = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
bi.width = 12.0f;
[buttons addObject:bi];
[bi release];

// Add profile button.
bi = [[UIBarButtonItem alloc] initWithTitle:@"Profile" style:UIBarButtonItemStylePlain target:self action:@selector(goToProfile)];
bi.style = UIBarButtonItemStyleBordered;
[buttons addObject:bi];
[bi release];

// Add buttons to toolbar and toolbar to nav bar.
[tools setItems:buttons animated:NO];
[buttons release];
UIBarButtonItem *twoButtons = [[UIBarButtonItem alloc] initWithCustomView:tools];
[tools release];
self.navigationItem.rightBarButtonItem = twoButtons;
[twoButtons release];   


其实还有其他方法,比如直接自定义NavigationBar 的View之类的

NavigationBar 的TitleView也是可以自定义的  有兴趣想了解更多自己看看API

你可能感兴趣的:(ios,NavigationBar,ButtonItem)