Monday, January 11, 2016

IOS UIButton's image aspect fit mode does not work

I encountered a problem with displaying image icons in UIButton elements in IOS. As shown in the screenshot below, the icon images are stretched out disregarding the aspect fit mode set in Xcode.

After troubleshooting the issue, I found that setting the UIButton's image content mode manually to scale by aspect fit will solve the problem.

In Xcode, I link all the buttons with icons to an outlet. Then I loop through the buttons and set the content mode property, as shown in the example code listing below.


@IBOutlet var filterButtons: [UIButton]?

//...etc...

override func viewDidLoad() {
     super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
        
//Workaround to keep the button icons scaled properly
   for button in filterButtons! {
       button.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
    }
}

The image buttons are now correctly rendered as shown in the screenshot below.

1 comment:

Felipe Augusto Sviaghin Ferri said...

Hmmm after reading your article it became obvious why setting the content mode on Xcode didn't work... That's because in the storyboard editor you set the aspect mode of the buttons view, and by your example we can see that we have to set the button's imageView content mode.

Here's a tip: an interesting place where you can set the buttons content mode is when setting the outlet:

@IBOutlet weak var sendPhotoButton: UIButton! {
didSet {
sendPhotoButton.imageView?.contentMode = .scaleAspectFill
}
}


Thanks for your article!