- (void)viewDidLoad
{
[super viewDidLoad];
//Load the image
UIImage *buttonImage = [UIImage imageNamed:@"1.png"];
//create the button and assign the image
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:buttonImage forState:UIControlStateNormal];
//sets the frame of the button to the size of the image
button.frame = CGRectMake(0, 0, buttonImage.size.width, buttonImage.size.height);
//creates a UIBarButtonItem with the button as a custom view
UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithCustomView:button];
customBarItem.target = self;
customBarItem.action = @selector(click:);
self.toolbarItems = [NSArray arrayWithObjects:customBarItem, nil];
}
- (void)click:(id)sender {
NSLog(@"action");
}
我认为当我按下barItem时,我的控制台将打印“动作”。 但是不打印“动作”。 我错过了什么吗? 谢谢你提前!
答案 0 :(得分:2)
试试这个
UIBarButtonItem *btn = [[UIBarButtonItem alloc] initWithTitle:@"Click ME!" style:UIBarButtonItemStyleBordered target:self action:@selector(click)];
.
.
.
-(void)click{
NSLog("hello");
}
答案 1 :(得分:1)
我认为问题在于,当您只是传递UIButton
时,[[UIBarButtonItem alloc] initWithCustomView
使用了UIView
,操作可能会转到UIButton
,不是UIBarButtonItem
。
而是这样做:
UIImageView *myImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"1.png"];
UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithCustomView:myImageView];
答案 2 :(得分:1)
我认为你正在尝试做更像这样的事情:
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:buttonImage forState:UIControlStateNormal];
[button setFrame:CGRectMake(0.0f, 0.0f, 25.0f, 25.0f)];
[button addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithCustomView:button];