UIButton没有在iOS中显示

时间:2011-08-17 10:06:04

标签: ios uibutton uiimage uibarbuttonitem displayobject

以下是显示工具栏按钮的代码。

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

[myButton setBackgroundImage:myImage forState:UIControlStateNormal];
UIBarButtonItem *myToolbarButton = [[UIBarButtonItem alloc] initWithCustomView:myButton];

UIButton myButton = [UIButton buttonWithType:UIButtonTypeCustom]; UIImage *myImage = [UIImage imageNamed:@"img1.png"]; [myButton setBackgroundImage:myImage forState:UIControlStateNormal]; UIBarButtonItem *myToolbarButton = [[UIBarButtonItem alloc] initWithCustomView:myButton];

工具栏上没有显示任何内容。请告诉我有什么问题。

3 个答案:

答案 0 :(得分:2)

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

或者如果它是导航栏

self.navigationItem.rightBarButtonItem = myToolbarButton;

此外,您应该为自定义按钮设置框架,如下所示:

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

然后,如果你想添加一个选择器/回调:

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

答案 1 :(得分:0)

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

其中self是UIViewController。

答案 2 :(得分:0)

您忘了将此按钮添加到工具栏中!

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];

如果要在导航栏中添加按钮,请使用:

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

此外,您应该记住设置myButton的框架:

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