UIButton ImageView Contentmode не работает - PullRequest
0 голосов
/ 24 мая 2019

Я только что запустил приложение для iOS в Swift, я занимаюсь дизайном программно (я имею в виду, что я не использую раскадровку)

У меня есть UIB-кнопка с изображением внутри, я хотел бы, чтобы изображениезаполнить всю кнопку.Прямо сейчас это просто показывает изображение в моей кнопке, но меньше, чем кнопка, центр в верхней части рамки кнопки.

Мой код:

    let buttonLocation = UIButton(frame: CGRect(x: 0, y: 0, width: buttonRoundedSize, height: buttonRoundedSize))
    buttonLocation.setImage(UIImage(named: "locate_button"), for: .normal)
    buttonLocation.backgroundColor = .white
    buttonLocation.layer.cornerRadius = frame.width / 2
    buttonLocation.myExtension()

Вот вещи, которые я 'мы попробовали (ни один из этих тезисов не сработал):

    self.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    self.autoresizingMask = .flexibleWidth
    self.autoresizingMask = .flexibleHeight
    self.imageView?.contentMode = .scaleAspectFill

Если я просто добавлю строку contentMode, она тоже не будет работать.ImageView не возвращает ноль, я проверял ..

Спасибо!

Ответы [ 4 ]

0 голосов
/ 24 мая 2019

Попробуйте использовать приведенный ниже код и удалите другие свойства, которые задаются для этой кнопки:

let buttonLocation = UIButton(frame: CGRect(x: 50, y: 50, width: 100, height: 100))
        buttonLocation.setImage(UIImage(named: "cat"), for: .normal)
        buttonLocation.backgroundColor = .white
        buttonLocation.layer.cornerRadius = 50
        buttonLocation.imageView?.contentMode = .scaleAspectFill
        buttonLocation.clipsToBounds = true

        self.view.addSubview(buttonLocation)

Здесь убедитесь, что изображение, которое вы устанавливаете в кнопке, больше, чем рамка кнопки.Вы можете изменить значения фрейма и угла в приведенном выше коде.Я только что попробовал с приведенным выше кодом и получить вывод ниже.

enter image description here

Вы можете оставить комментарий, если это не ваш ожидаемый результат.

Надеюсь, это поможет.

0 голосов
/ 24 мая 2019

вам нужно использовать свойство setBackgroundImage вместо setImage.

buttonLocation.setBackgroundImage(UIImage(named: "locate_button"), for: .normal)
0 голосов
/ 24 мая 2019

Может быть, это поможет вам:

let buttonLocation = UIButton(type: .custom)
buttonLocation.frame = CGRect(x: 0, y: 0, width: buttonRoundedSize, height: buttonRoundedSize)
buttonLocation.setImage(UIImage(named: "locate_button"), for: .normal)
buttonLocation.imageView?.contentMode = .scaleAspectFill
buttonLocation.contentHorizontalAlignment = .fill
buttonLocation.contentVerticalAlignment = .fill
buttonLocation.backgroundColor = .white
buttonLocation.layer.cornerRadius = frame.width / 2
buttonLocation.clipsToBounds = true

Вам нужно добавить свойства contentHorizontalAlignment и contentVerticalAlignment и не забудьте установить clipsToBounds в значение true, чтобы увидеть эффект углового рауса.

0 голосов
/ 24 мая 2019

Установите contentMode из buttonLocation's imageView как scaleAspectFill или scaleToFill, чтобы охватить все frame из button.

let buttonLocation = UIButton(frame: CGRect(x: 0, y: 0, width: 200, height: 500))
buttonLocation.setImage(UIImage(named: "image"), for: .normal)
buttonLocation.backgroundColor = .gray
buttonLocation.layer.cornerRadius = buttonLocation.frame.width / 2
buttonLocation.imageView?.contentMode = .scaleAspectFill //Here........

Пример:

enter image description here

...