Подтвердить что ты не робот

UIButton не поддерживает Aspect Fill contentMode после изменения размера анимации

Я использую автоматический макет. Ниже приведено исходное состояние представления.

В центре находится кнопка, содержащаяся в представлении. На кнопке есть вкладка ContentMode Aspect Fill, и изображение устанавливается в качестве фонового изображения кнопки.

enter image description here

Затем я использую следующий код для преобразования вида, который увеличит центральную карту, чтобы заполнить экран, и переместите изображение в верхнюю часть представления:

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

        }

Результат:

enter image description here

Однако это не то, что я хочу. Кнопка не соблюдает contentMode, а затем изображение растягивается.

Может ли кто-нибудь сказать мне, как поддерживать Aspect Fill contentMode кнопки?

4b9b3361

Ответ 1

  • Установите тип кнопки UIButtonTypeCustom ( "Пользовательский" в раскадровке или xib).
  • Установите изображение кнопки, а не фоновое изображение кнопки.
  • В viewDidLoad установите button.imageView.contentMode в UIViewContentMode.ScaleAspectFill.

Ответ 2

Swift 3


Отключение ответа Роба:

    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

Ответ 3

Swift 2

button.imageView?.contentMode = UIViewContentMode.ScaleAspectFit

все contentMode:

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

Ответ 4

Попробуйте это перед использованием [btn setImage: forState:]:

    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
    btn.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;
  • Swift 4
//Center
btn.contentHorizontalAlignment = UIControl.ContentHorizontalAlignment.center

//Left
btn.contentHorizontalAlignment = UIControl.ContentHorizontalAlignment.left

//Right
btn.contentHorizontalAlignment = UIControl.ContentHorizontalAlignment.right

Ответ 5

версия 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)

Ответ 6

Swift 4.2

расширение

// 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: newValue),
                self.imageView != nil {
                self.imageView?.contentMode = mode
            }
        }
    }
}

UPDATE: Этот и другие ответы не работают для меня в ios 11. Самый близкий ответ - @Jaro, но я думаю, что лучше сделать UIImageView, а над ним добавить кнопку или создать пользовательский класс UIImageView, который будет иметь распознаватель жестов и анимация кликов.

Ответ 7

В Xcode 10.1 вы можете использовать интерфейсный конструктор. В инспекторе атрибутов справа используйте раздел "Управление" следующим образом:

ios swift xcode 10.1 uibutton scale to fill

Ответ 8

Язык, кажется, был обновлен.

Мне пришлось копнуть немного глубже, чтобы получить решение xscoder для:

myButton.imageView.contentMode = .ScaleAspectFill 

обновленная версия выглядит следующим образом:

myButton.imageView?.contentMode = UIView.ContentMode.scaleAspectFit

Ответ 9

Вы можете подклассифицировать кнопку и добавить их:

class FitButton: UIButton {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)


    }

    override func layoutSubviews() {
        self.imageView?.contentMode = .scaleAspectFill
        self.contentHorizontalAlignment = .fill
        self.contentVerticalAlignment = .fill
        super.layoutSubviews()


    }

}

Ответ 10

может помочь кому-то

button.subviews.first?.contentMode = .scaleAspectFit

Ответ 11

стриж

для кнопки имеет ContentMode Aspect Fill:

btn.contentHorizontalAlignment = .fill
btn.contentVerticalAlignment = .fill
btn.imageView?.contentMode = .scaleAspectFill