Question

This is the first time I have ever designed an iOS app so I want to make sure I understand this behavior correctly.

I designed a custom bar button icon for a navigation bar in Photoshop. The final image that I saved in Photoshop was 102 x 45, and yes I realize that these dimensions are bigger than the recommended 44x44 in the iOS 7 design guidelines.

Anyways, I placed my image into the asset folder, and then programmatically set the bar button item with the following code:

UIImage* firstButtonImage = [UIImage imageNamed:@"loginbutton1"];

    CGRect frame = CGRectMake(0, 0, 102, 45);

    UIButton * someButton = [[UIButton alloc] initWithFrame:frame];
    [someButton setBackgroundImage:firstButtonImage forState:UIControlStateNormal];
    [someButton addTarget:self action:@selector(didTapLoginButton:)
         forControlEvents:UIControlEventTouchUpInside];

    self.rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:someButton];

    self.navItem.rightBarButtonItem = self.rightBarButton;

As you can see I set the frame's width and height to the exact size of the image. When I first ran the app, I didn't like the image and thought it was too big. So I changed the width and height parameters in this statement:

CGRect frame = CGRectMake(0, 0, 70, 30);

And now the image looks perfect on the iPhone screen. This is on an iPhone 4s.

So my main question is, what is actually happening when I change the frame size? Since the frame is now smaller than the actual image size, does the image just get scaled down automatically to fit inside the frame?

Was it helpful?

Solution

Yes the image get scaled because you are using backgroundImage (not Image). Both images have different behaviors.

Check the Xcode Interface Builder, you can see there, that you can set two images: Image and Background. Background is the UIImage that get scaled for the whole frame of the UIButton.

enter image description here

The UIButton Class Reference allows you to access the imageView of the image (not theimageView of the backgroundImage)

Because you have access to the imageView, you can change the mode of the image with:

[[someButton imageView] setContentMode:UIViewContentModeBottomLeft];

In UIView Class Reference you can check all the UIViewContentModes provided by Apple.

You can check that changing a little bit your code:

[someButton setImage:firstButtonImage forState:UIControlStateNormal];
[[someButton imageView] setContentMode:UIViewContentModeBottomRight];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top