我正在使用自动布局。以下是 View 的初始状态。

中心是 View 中包含的按钮。该按钮具有contentMode宽高比填充,并且该图像被设置为该按钮的背景图像。

然后,我使用以下代码转换 View ,这将放大中心卡以填充屏幕,并将图像移至 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

        }

结果是:

但是,这不是我想要的。该按钮不遵守contentMode,然后图像被拉伸(stretch)。

谁能告诉我如何维护按钮的纵横比填充contentMode?

最佳答案

  • 将按钮类型设置为UIButtonTypeCustom( Storyboard 或xib中的“自定义”)。
  • 设置按钮的图像,而不是按钮的背景图像。
  • viewDidLoad中,将button.imageView.contentMode设置为UIViewContentMode.ScaleAspectFill
  • 关于ios - 调整动画大小后,UIButton不遵守Aspect Fill contentMode,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26263231/

    10-08 21:57