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を押すと、コンソールに「アクション」が出力されると思います。ただし、「アクション」は出力されません。私は何かを逃しましたか?よろしくお願いします!

4

3 に答える 3

2

これを試して

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

.
.
.

-(void)click{
    NSLog("hello");
}
于 2012-07-17T12:19:10.867 に答える
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];
于 2012-07-17T12:25:38.657 に答える
1

問題は、単に a を渡す必要があるときにaUIButtonを for に使用していることだと思います。アクションはおそらくではなく に行きます。[[UIBarButtonItem alloc] initWithCustomViewUIViewUIButtonUIBarButtonItem

代わりにこれを行います:

UIImageView *myImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"1.png"];
UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithCustomView:myImageView];
于 2012-07-17T12:23:55.623 に答える