想要做出像是 IG 一樣可以點選的圖片,可以用 Button 的 image 顯示圖片。但如果 image 的尺寸比 Button 大,image 會直接無視 Button 外框、直接爆破 Button

兔兔是 Button 內的 image

在 iOS 15,想讓 button 的圖片不變形,我們可透過 UIButton.Configuration 讓圖片維持比例且在適當的大小

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

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

利用 Capsule 實現圓形 button

  • 此時按 Button 時圖片不會變色

上方的兔子按鈕是背景藍色部分變色(兔子圖有去背),藍色部分是 Button 本身的顏色所以會變色

下方使用未去背的圖片,按了完全不會變色,可另用程式設定,可參考最上方彼得教學

用程式設定

若是用程式產生 Button,是設定 UIButton.Configuration

let button = UIButton(type: .system)
var config = UIButton.Configuration.plain()
config.background.image = UIImage(named: "rabbit")
config.background.imageContentMode = .scaleAspectFill
button.configuration = config

button.frame = CGRect(x: 100, y: 100, width: 200, height: 200)
view.addSubview(button)

按住 button 時換圖

用程式設定,參考最上方彼得教學文

--

--