I have a button in my UIToolbar that I've assigned an image to, but I'd like for the image to automatically be scaled down (resizing the image outside of the app lowers some of its quality).
I attempted the solution here which creates a custom imageView and then assigns it to the button. However, the image doesn't seem to be appearing. Here's my code:
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"info.png"]];
imageView.frame = CGRectMake(0, 0, 35, 35);
imageView.contentMode = UIViewContentModeScaleAspectFit;
imageView.userInteractionEnabled = YES;
UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:imageView];
self.tutorial_lbl = barButtonItem;
Note that if I comment out the last two lines and use the below line instead, the image does appear but then it loses the action of the button.
[self.tutorial_lbl setCustomView:imageView];
I assume that adding a custom view does the same thing as when you use initWithCustomView: to create the bar button item. In that case, the docs say,
The bar button item created by this method does not call the action method of its target in response to user interactions. Instead, the bar button item expects the specified custom view to handle any user interactions and provide an appropriate response.
So, you should add a tap gesture recognizer to the image view, and set an action method for it,
- (void)viewDidLoad {
[super viewDidLoad];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 35, 35)];
imageView.image = [UIImage imageNamed:@"info.png"];
UITapGestureRecognizer *tapper = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(barButtonTapped:)];
[imageView addGestureRecognizer:tapper];
imageView.userInteractionEnabled = YES;
[self.tutorial_lbl setCustomView:imageView];
}
-(void)barButtonTapped:(UITapGestureRecognizer *) sender {
NSLog(@"Tapped");
}