How to add barbutton programmatically with image

匆匆过客 提交于 2019-12-02 03:17:00
UIImage *image = [UIImage imageNamed:@"request.png"];    
UIButton* requestButton = [UIButton buttonWithType:UIButtonTypeCustom];
[requestButton setImage:image forState:UIControlStateNormal];
[requestButton addTarget:self action:@selector(requestButton) forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *button2 = [[UIBarButtonItem alloc] initWithCustomView:requestButton];
self.navigationItem.rightBarButtonItem = button2;

I do this normally this way:

self.myButton = [UIButton buttonWithType:UIButtonTypeCustom];

[myButton setImage:[UIImage imageNamed:@"button_normal.png"] forState:UIControlStateNormal];
[myButton setImage:[UIImage imageNamed:@"button_pressed.png"] forState:UIControlStateHighlighted];
myButton.frame = CGRectMake(0, 0, 121, 36);

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

UIBarButtonItem * aBarButton = [[[UIBarButtonItem alloc] initWithCustomView:myButton] autorelease];

[toolbar setItems:[NSArray arrayWithObjects:aBarButton, nil]];
girish
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];

[myButton setImage:[UIImage imageNamed:@"request-1.png"] forState:UIControlStateNormal];

myButton.frame = CGRectMake(0, 0, 80, 36);

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

UIBarButtonItem * aBarButton = [[[UIBarButtonItem alloc] initWithCustomView:myButton] autorelease];


self.navigationItem.rightBarButtonItem = aBarButton;



[myButton release];

I usually create the UIImageView, then a UITapGestureRecognizer and i add it to the UIImageView, and finally i create the UIBarbuttonItem:

    //UIImageView where the image is shown
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"imageName"]];
    imageViewSettings.frame = CGRectMake(0, 0, 25, 25);
    imageViewSettings.contentMode = UIViewContentModeScaleAspectFit;

    //TapGesture
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(methodToTrigger)];

    //Adding the gesture to the ImageView
    [imageView addGestureRecognizer:tapGesture];

    //Creating the barButtonItem
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:imageView];

    //Finally add the button to the navigationBar
    self.navigationItem.rightBarButtonItem = barButtonItem;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!