开发者

UIButton not showing in iOS

Following is a code to display a button to the toolbar.

UIButton myButton = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *myImage = [UIImage imageNamed:@"img1.png"];

[myButton setBackground开发者_如何学运维Image:myImage forState:UIControlStateNormal];
UIBarButtonItem *myToolbarButton = [[UIBarButtonItem alloc] initWithCustomView:myButton];

Nothing gets displayed on the toolbar. Please tell me what is wrong.


[myToolbar setItems:[NSArray arrayWithObject:myToolbarButton]]; // might help

OR if it's a navigation bar

self.navigationItem.rightBarButtonItem = myToolbarButton;

Also you should set the frame for the custom button, something like this:

UIButton *mybutton = [[UIButton alloc] initWithFrame:CGRectMake:0,0,200,50];

Then if you want to add a selector/callback:

[myButton addTarget:self action:@selector(someMethod) forControlEvents:UIControlEventTouchUpInside];


self.navigationItem.leftBarButtonItem = myButtonItem; // and change for the right button.

Where self is a UIViewController.


You forgot to add this button to the toolbar!

NSArray *toolbarItems = [[NSArray alloc] initWithObjects:myToolbarButton,nil]; // you can more buttons here
[aToolbar setItems:toolbarItems animated:NO]; // change to YES if you want to have nice animation
[toolbarItems release];

If you want to add a button to navigation bar, use this:

[self.navigationItem setRightBarButtonItem:myToolbarButton]; // or setLeft...

Also, you should remember to set the frame of myButton:

[myButton setFrame:CGRectMake(0, 0, 30, 32)];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜