Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the embedded button of UIBarButtonItem

In an iPhone app,we can make a UIBarButtonItem by using the following code:

UIBarButtonItem *bbix=[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:nil action:nil];

the generated UIBarButtonItem has a system-provided "action" icon.My question is :how to get this UIBarButtonItem's inner UIButton and add this UIButton to another UIView? who can show me some code?

like image 540
Jagie Avatar asked Jun 13 '10 07:06

Jagie


3 Answers

You can't. UIBarButtonItem inherits from UIBarItem which inherits from NSObject. None of those classes has a method to get a UIButton, because UIBarButtonItem isn't a UIButton.

Contrariwise, you can create a UIBarButtonItem from a UIButton -- see an answer I gave to a different question for more info (which works by adding it as a "custom view").

like image 161
Shaggy Frog Avatar answered Oct 25 '22 13:10

Shaggy Frog


Accessing the "customView" property of the bar button item is one possible solution:

UIBarButtonItem *item = (UIBarButtonItem *)[self.navigationItem.rightBarButtonItems objectAtIndex:0];
                     OR
UIBarButtonItem *item = (UIBarButtonItem *)[self.navigationItem.rightBarButtonItem];

UIButton *myBtn;

if([item.customView isKindOfClass:[UIButton class]]) 
{ 
    myBtn = (UIButton*)item.customView;
}

if(myBtn)
{
    // do something
}

Try this out. It really works for me :)

like image 35
Augustine Avatar answered Oct 25 '22 11:10

Augustine


I don't think you can get the embedded button in any case. However, if you create a button using a custom view, for example, using a button, we can get that button later using this code:

((UIButton *)(theBarButtonItem.customView.subviews.lastObject));

The hierarchy of the custom view should like this:

|--UIView
  |--UIButton
  |--UIImageView

Hopes that helps.

like image 43
D.D. Avatar answered Oct 25 '22 11:10

D.D.