利用 iOS 15 的 UIButton.Configuration 實現圖片維持比例的 button,圓形 button & 點選時變色

開發 iOS App 時,我們時常會想要圖片可以點選,其中的一個方法是用 button 的 image 顯示圖片。不過 button 顯示圖片時要注意變形問題。當 button 尺寸小於圖片尺寸時,若 button 的比例和圖片比例不同,圖片縮小顯示時將變形,因此須另外調整 button 的 imageView?.contentMode。

在 iOS 15,想讓 button 的圖片不變形有新的做法,我們可透過 UIButton.Configuration 實現圖片維持比例的 button。

加入 Button 元件

將 button 的 Title 清除,Background Configuration 下的 Background 設為 Custom

從 Background Configuration 下的 Image 設定背景圖片,將 Content Mode 設為 Aspect Fill

Aspect Fill 將讓圖片維持比例填滿整個 button。

以上 Interface Builder 的設定其實是設定 UIButton.Configuration,對應的程式寫法如下。

let button = UIButton(type: .system)
var config = UIButton.Configuration.plain()
config.background.image = UIImage(named: "klaus1")
config.background.imageContentMode = .scaleAspectFill
button.configuration = config
button.frame = CGRect(x: 100, y: 100, width: 200, height: 200)
view.addSubview(button)

Cool,我們實現維持圖片比例的 button 了。

範例圖片是好看的電影 Klaus

利用 Capsule 實現圓形 button

當 button 比例是正方形時,將 Background Configuration 下的 Corner Style 設為 Capsule 即可讓它變成完美的圓形。

不過目前有個小小的缺點,點選 button 時圖片不會有變色的效果。以下我們分別示範點選 button 時變色跟換圖的效果。

按住 button 時變色

方法 1:

新增繼承 UIButton 的類別 ImageButton,在它的 init 設定 button 的 configurationUpdateHandler。configurationUpdateHandler 將在 button 狀態改變時觸發,我們在裡面依據 isHighlighted 是否為 true 設定 button 的透明度, button 按著時 isHighlighted 為 true,此時我們將 button 變成半透明。

class ImageButton: UIButton {

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

configurationUpdateHandler = { button in
button.alpha = button.isHighlighted ? 0.5 : 1
}
}

}

將 Interface Builder 畫面裡的按鈕類別改成 ImageButton。

方法 2:

將 Interface Builder 畫面裡的按鈕連到 outlet button,然後在 didSet 裡設定 button 的 configurationUpdateHandler。

class ViewController: UIViewController {

@IBOutlet weak var button: UIButton! {
didSet {
button.configurationUpdateHandler = { button in
button.alpha = button.isHighlighted ? 0.5 : 1
}

}
}
}

按住 button 時換圖

依據 isHighlighted 顯示不同的背景圖片。

方法 1:

class ImageButton: UIButton {

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

configurationUpdateHandler = { button in

var config = button.configuration
config?.background.image = button.isHighlighted ? UIImage(named: "klaus2") : UIImage(named: "klaus1")
button.configuration = config
}
}

}

方法 2:

class ViewController: UIViewController {

@IBOutlet weak var button: UIButton! {
didSet {
button.configurationUpdateHandler = { button in
var config = button.configuration
config?.background.image = button.isHighlighted ? UIImage(named: "klaus2") : UIImage(named: "klaus1")
button.configuration = config
}
}
}

}

--

--

彼得潘的 iOS App Neverland
彼得潘的 Swift iOS App 開發問題解答集

彼得潘的iOS App程式設計入門,文組生的iOS App程式設計入門講師,彼得潘的 Swift 程式設計入門,App程式設計入門作者,http://apppeterpan.strikingly.com