iPhone UIBarButtonItem setCustomView: method?
I want to customize my UIBarButtonItem's appearance. Here's the code I'm currently using:
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(267, 6, 48, 30)];
[editButton setCustomView:button]; // editButton is the UIBarButtonItem
Unfortunately, the UIButton does not get drawn, i.e. it's 100% transparent. I know the button is there because when I add a line to the code, like so:
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(267, 6, 48, 30)];
[editButton setCustomView:button]; // e开发者_开发问答ditButton is the UIBarButtonItem
UIRectFill(button.frame);
I see a black square appearing in the position where the button should appear.
How can I get my UIButton to be drawn? I already looked at a ton of places, but nothing seems to work ...
I don't think you can set the custom view of a button to another button. Buttons are complex objects and nesting them like that usually won't work.
The custom view attribute is supposed to be for decoration, not functionality. You should load a custom view with appearance you want for the UIBarButtonItem and let it handle the actual button logic.
Did you try to init it with a Custom view that is a UIImageView ? If it works you could create the UIImageView in such a way that it fakes a classic UIButton as described here :
How can I create a big, red UIButton with the iPhone SDK?
But more generally, from a UI perspective, it's strange to have classic "UIButton" at the place of "UIBarButtonItem" :/
Consult my answer to this question.
I think it's best to avoid putting a UIButton
inside a UIBarButtonItem
. They do the same thing more or less, and BBIs exist for a reason - they're lightweight compared to UIButtons, and they have a nice cozy relationship with UINavigationItems
.
I think we can help a little better if you let us know - what is the overall purpose you're trying to achieve? That way we can help provide a viable solution.
I was having a similar problem; the button didn't appear and tapping in that space did nothing, either. Setting the bounds of the button seemed to be the magic that makes it work.
Here's the code that I'm using to set the right button:
UIButton* addButton = [UIButton buttonWithType:UIButtonTypeCustom];
[addButton addTarget:self action:@selector(onAdd) forControlEvents:UIControlEventTouchUpInside];
[addButton setImage:[UIImage imageNamed:@"button_plus.png"] forState:UIControlStateNormal];
addButton.bounds = CGRectMake(0, 0, 30, 30);
UIBarButtonItem* addItem = [[UIBarButtonItem alloc] initWithCustomView:addButton];
navitem.rightBarButtonItem = addItem;
精彩评论