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.
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:
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?
UIButtonTypeCustom
(“Custom” in a storyboard or xib).viewDidLoad
, set button.imageView.contentMode
to UIViewContentMode.ScaleAspectFill
.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With