user1120133 user1120133 - 2 months ago 13
iOS Question

Dismiss ModalView Programmatically by done button

I have to click on done button to dismiss modalview programmatically. I think

UIButton
is better than
UIBarButtonItem
to add
UIControlEventsTouchupInside
.

But with
UIButton
I'm confused what buttontype should use.

UIButton *button = [UIButton buttonWithType:UIButtonTypeInfoLight];

[button addTarget:self action:@selector(displayModalViewaction:) forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem * button = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
target:self
action:@selector(dismissViewaction:)] autorelease];

Answer Source

You will most likely want to use UIButtonTypeRoundedRect or UIButtonTypeCustom

With the custom type, you can add images for display.
You can try "stealing" these images from the UIBarButtonItem (image property defined in UIBarItem) and making the custom button look like the UIBarButtonSystemItemDone button

UIBarButtonItem * buttonForImage = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:nil                                                                       action:nil] autorelease];

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

[button addTarget:self action:@selector(displayModalViewaction:) forControlEvents:UIControlEventTouchUpInside];

[button setImage:buttonForImage.image forState:UIControlStateNormal];

Things to look out for. When setting an image for a UIButton, it does not scale to the size of the button according to contentMode property. If you want the image to follow the rules of the contentMode property, use setBackgroundImage: forState: instead.