Thursday, May 30, 2013

UIBarButtonItem initWithCustomView example in Objective C (iOS).


UIBarButtonItem initWithCustomView

Initializes a new item using the specified custom view.

- (id)initWithCustomView:(UIView *)customView

Parameters
customView
A custom view representing the item.

Return Value
Newly initialized item with the specified properties.

Discussion of [UIBarButtonItem initWithCustomView]
The bar button item created by this method does not call the action method of its target in response to user interactions. Instead, the bar button item expects the specified custom view to handle any user interactions and provide an appropriate response.

UIBarButtonItem initWithCustomView example.
UIButton *logoButton = [UIButton buttonWithType:UIButtonTypeCustom];
[logoButton setImage: [UIImage imageNamed:@"icon.png"] forState:UIControlStateNormal];
logoButton.frame = CGRectMake(0, 0, 30, 30);
[logoButton addTarget:self action:@selector(showAbout:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *barItem = [[UIBarButtonItem alloc] initWithCustomView:logoButton];
self.navigationItem.rightBarButtonItem = barItem;
[barItem release];

Example of [UIBarButtonItem initWithCustomView].
UIImageView *SOCImageView = [[UIImageView alloc] initWithImage:
                             [UIImage imageNamed:@"cancel_wide.png"]];

UITapGestureRecognizer *tapGesture =
       [[UITapGestureRecognizer alloc] initWithTarget:self
                                               action:@selector(deselectAll:)];
[SOCImageView addGestureRecognizer:tapGesture];

SOItem.leftBarButtonItem =
       [[UIBarButtonItem alloc] initWithCustomView:SOCImageView];
[SOCImageView release];

UIBarButtonItem initWithCustomView example.
UIButton *toggleKeyboardButton = [UIButton buttonWithType:UIButtonTypeCustom];
toggleKeyboardButton.bounds = CGRectMake( 0, 0, keyboardAddImage.size.width, keyboardAddImage.size.height );
[toggleKeyboardButton setImage:keyboardAddImage forState:UIControlStateNormal];
[toggleKeyboardButton addTarget:self action:@selector(toggleKeyboard) forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *toggleKeyboardItem = [[UIBarButtonItem alloc] initWithCustomView:toggleKeyboardButton];
//[toggleKeyboardItem setTarget:self];
//[toggleKeyboardItem setAction:@selector(toggleKeyboard:)];

End of UIBarButtonItem initWithCustomView example article.