Question

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];
Was it helpful?

Solution

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");
}

OTHER TIPS

One thing you could try to do is set the image insets. Both UIButton and UIBarButtonItem support image insets. You do not need to add a UIImageView for this. Just set the image on your button and then set the image insets.

myButton.imageEdgeInsets = UIEdgeInsetsMake(TOP, LEFT, BOTTOM, RIGHT);//UIButton

myBarButtonItem.imageInsets = UIEdgeInsetsMake(TOP, LEFT, BOTTOM, RIGHT);//UIBarButtonItem

This resizes the images on the buttons. Positive values will decrease the size, while negative values will enlarge the image.

I was able to achieve this by doing the following:

let originalImage = UIImage(named: "SearchIcon")
let scaledIcon = UIImage(CGImage: originalImage!.CGImage!, scale: 5, orientation: originalImage!.imageOrientation)
let rightButton = UIBarButtonItem(image: scaledIcon, style: .Plain, target: self, action: #selector(MeViewController.showSearchUsers))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top