views:

471

answers:

2

Hi there,

Well, the title says it all. I'd like to have a UIViewController which has an Add and a Trash button both right to the title, either by adding two UIBarButtonItems to the navigation item/bar or by adding them to a UISegmentedControl and then adding the SegmentedControl to the item. Is this possible? If yes, how is it achieved best?

Cheers

MrMage

A: 

I have done something similar. I've added two UIButtons to a navigation item/bar by creating a UIView subclass that has two UIButtons in it. You can then do something like this:

MyUIViewSubclass *tempview = [[[MyUIViewSubclass alloc] initWithFrame:CGRectMake(234,4,84,30)] autorelease];
UIBarButtonItem newButton = [[[UIBarButtonItem alloc] initWithCustomView:tempview] autorelease];
[self.navigationItem setRightBarButtonItem:newButton animated:NO];

All you have to do is layout the buttons in MyUIViewSubclass and you're good.

Also, I pass the ID of the target along in a customized init command to make for easier targeting of the buttons in the view. So for MyUIViewSubclass instead of initWithFrame, I have something like this:

- (id)initWithFrame:(CGRect)aRect andTarget:(id)newTarget {
    if (self = [super initWithFrame:aRect]) {



        UIButton *editbtn = [[[UIButton alloc]  initWithFrame:fframe] autorelease];
        [editbtn addTarget:newTarget action:@selector(MBEdit) forControlEvents:UIControlEventTouchUpInside];

        [self addSubview:editbtn];
        [self setFirstbutton:editbtn];
        [editbtn release];



        UIButton *newbtn = [[[UIButton alloc]  initWithFrame:fframe] autorelease];
        [newbtn addTarget:newTarget action:@selector(MBNew) forControlEvents:UIControlEventTouchUpInside];

        [self addSubview:newbtn];
        [self setSecondbutton:newbtn];
        [newbtn release];

    }

    return self;

}
mjdth
But I'd still have to paint the UIButtons myself to have them look like the navigation bar buttons, right? I'd be perfectly happy to use a UISegmentedControl (which would save me the painting hassle) - but what I really need are the + and the original iPhone trash can icons. I'd prefer an even more elegant solution (like having some Unicode letter codes for the bold + and the trash can), though.
MrMage
I actually just took a screenshot and used the image for my buttons. I'm almost certain that you can also just add a segmented control to the view instead of two buttons. That would work just as well.
mjdth
A: 

You can add multiple buttons to a navigation item by wrapping them in a UIToolbar, sample code.

zoul