2012-07-17 74 views
0
- (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。 但是「行動」不打印。 我錯過了什麼嗎? 感謝您的提前!UIBarButtonItem target-action does not invoke

回答

1

我相信問題是,你使用的是UIButton[[UIBarButtonItem alloc] initWithCustomView時,你應該簡單地傳遞一個UIView,動作很可能將在UIButton而不是UIBarButtonItem

而是這樣做:

UIImageView *myImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"1.png"]; 
UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithCustomView:myImageView]; 
2

試試這個

UIBarButtonItem *btn = [[UIBarButtonItem alloc] initWithTitle:@"Click ME!" style:UIBarButtonItemStyleBordered target:self action:@selector(click)]; 

. 
. 
. 

-(void)click{ 
    NSLog("hello"); 
} 
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];