Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIButton not respect Aspect Fill contentMode after resizing animation

Tags:

ios

swift

ios8

I am use auto layout. Following is the initial state of the view.

In the centre is a button contained in a view. The button has contentMode Aspect Fill, and the image is set as the background image of the button.

enter image description here

Then I use the following code to transform the view, which will enlarge the centre card to fill the screen, and move the image to the top of the view:

cardTrailingSpaceConstraint.constant = 0 cardLeadingSpaceConstraint.constant = 0 cardView.removeConstraint(cardAspectRatioConstraint) let cardHeightConstraint = NSLayoutConstraint(item: cardView, attribute: .Height, relatedBy: .Equal, toItem: view, attribute: .Height, multiplier: 1.0, constant: 0) view.addConstraint(cardHeightConstraint)  dishImageButton.removeConstraint(dishButtonBottomSpaceConstraint) let dishButtonHeightConstraint = NSLayoutConstraint(item: dishImageButton, attribute: .Height, relatedBy: .Equal, toItem: cardView, attribute: .Height, multiplier: 0.2, constant: 0) cardView.addConstraint(dishButtonHeightConstraint)  cardView.setNeedsUpdateConstraints() UIView.animateWithDuration(0.7, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.7, options: nil, animations: { [unowned self] () -> Void in     self.cardHeader.alpha = 0     self.cardView.layer.cornerRadius = 0     self.cardView.layoutIfNeeded()      }) { [unowned self] (finished) -> Void in          } 

The result is:

enter image description here

However, it is not what I want. The button is not respecting the contentMode and the image then get stretched.

Can anyone tell me how to maintain the Aspect Fill contentMode of the button?

like image 798
HanXu Avatar asked Oct 08 '14 17:10

HanXu


2 Answers

  1. Set the button type to UIButtonTypeCustom (“Custom” in a storyboard or xib).
  2. Set the button's image, not the button's background image.
  3. In viewDidLoad, set button.imageView.contentMode to UIViewContentMode.ScaleAspectFill.
like image 195
rob mayoff Avatar answered Sep 22 '22 21:09

rob mayoff


Swift 3


Going off of Rob's answer:

    let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 80, height: 30))     btn.setImage(UIImage(named: "albumsBtn"), for: UIControlState.normal)     btn.imageView?.contentMode = UIViewContentMode.scaleAspectFit     btn.addTarget(self.navigationController, action: #selector(CustomGalleryViewController.showAlbums(_:)), for:  UIControlEvents.touchUpInside)     let item = UIBarButtonItem(customView: btn)     self.navigationItem.leftBarButtonItem = item 
like image 40
Jessie Avatar answered Sep 21 '22 21:09

Jessie