UIButton不尊重Aspect在调整animation大小后填充contentMode

我使用自动布局。 以下是视图的初始状态。

在中心是一个包含在视图中的button。 该button具有contentMode Aspect Fill,并且图像被设置为button的背景图像。

在这里输入图像说明

然后,我使用下面的代码来转换视图,这将放大中心卡填充屏幕,并将图像移动到视图顶部:

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 } 

结果是:

在这里输入图像说明

但是,这不是我想要的。 该button不尊重contentMode,然后图像被拉伸。

任何人都可以告诉我如何保持button的方面填充contentMode?

  1. 将buttontypes设置为UIButtonTypeCustom (在故事板或xib中的“自定义”)。
  2. 设置button的图像,而不是button的背景图像。
  3. viewDidLoad ,将button.imageView.contentMode设置为UIViewContentMode.ScaleAspectFill

Swift 3


从Rob的回答中走出来:

  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 

Swift 2.x版本:

 let myButton = UIButton(type: .Custom) myButton.frame = CGRectMake(0, 0, 200, 20) myButton.backgroundColor = UIColor.blackColor() myButton.imageView.contentMode = .ScaleAspectFill // ALTERNATIVE: .ScaleAspectFit myButton.setImage(UIImage(named: "myImageName"), forState: .Normal) myButton.addTarget(self, action: #selector(buttonAction), forControlEvents: .TouchUpInside) view.addSubview(myButton) 

Swift 2

 button.imageView?.contentMode = UIViewContentMode.ScaleAspectFit 

所有contentMode:

  .ScaleToFill .ScaleAspectFit .ScaleAspectFill .Redraw .Center .Top .Bottom .Left .Right .TopLeft .TopRight .BottomLeft .BottomRight 

斯威夫特4

延期

 // Inspectable image content mode extension UIButton { /// 0 => .ScaleToFill /// 1 => .ScaleAspectFit /// 2 => .ScaleAspectFill @IBInspectable var imageContentMode: Int { get { return self.imageView?.contentMode.rawValue ?? 0 } set { if let mode = UIViewContentMode(rawValue: imageContentMode), self.imageView != nil { self.imageView?.contentMode = mode } } } }