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.

No comments:

Related Posts with Thumbnails