iOS15新出的按鈕外觀設定,變成像吃設定檔的方式
在一些圓角設定、圖片換位置好像有比較好用😗
button.configuration = plainConfig
button.updateConfiguration() // 有需要更新的話
let plainConfig: UIButton.Configuration = {
// 普通按鈕
var config = UIButton.Configuration.plain()
config.title = "我是按鈕"
return config
} ()
config.cornerStyle = .capsule
完整code(圓角+背景填充+圖片放右邊)
let corneredConfig: UIButton.Configuration = {
// 背景填充
var config = UIButton.Configuration.filled()
config.baseBackgroundColor = .systemMint
// 圓角設定
config.cornerStyle = .capsule
// 設定圖片
config.image = UIImage(systemName: "paperplane")
// 圖片&標題對應位置
config.imagePlacement = .trailing
// 圖片&標題距離
config.imagePadding = 5.0
// 設定標題字型顏色
var titleAttributes = AttributeContainer()
titleAttributes.foregroundColor = UIColor.black
titleAttributes.font = UIFont.systemFont(ofSize: 15.0)
let title = AttributedString("送出", attributes: titleAttributes)
config.attributedTitle = title
return config
} ()
預設是Dynamic,會隨著dynamic字型改變。測試了一下大中小type
好像大圓角比較明顯,另外兩個差不多
config.background.cornerRadius = 15.0
config.background.strokeColor = .systemMint
config.background.strokeWidth = 2.0
// 圖片&標題對應位置
config.imagePlacement = .trailing
// 圖片&標題距離
config.imagePadding = 5.0
效果還不錯,all和leading看起來是一樣的
覺得這是最棒的改變,以前改個圖片位置超麻煩,用EdgeInset改來改去🙁
先做一個普通的邊框按鈕設定
var borderedConfig: UIButton.Configuration = {
var config = UIButton.Configuration.plain()
config.background.backgroundColor = .white
config.cornerStyle = .capsule
config.image = UIImage(systemName: "paperplane")?.withTintColor(.systemMint, renderingMode: .alwaysOriginal)
// 圖片&標題距離
config.imagePadding = 5.0
// 設定標題字型顏色
var titleAttributes = AttributeContainer()
titleAttributes.foregroundColor = UIColor.systemMint
titleAttributes.font = UIFont.systemFont(ofSize: 15.0)
let title = AttributedString("送出", attributes: titleAttributes)
config.attributedTitle = title
// 設置邊框
config.background.strokeColor = .systemMint
config.background.strokeWidth = 2.0
return config
} ()
borderedConfig.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { [weak self] incoming in
var outgoing = incoming
if let self, self.plainButton.isSelected {
outgoing.foregroundColor = UIColor.white
} else {
outgoing.foregroundColor = UIColor.systemMint
} return outgoing
}
func updateButtonConfiguration() {
var config = plainButton.configuration
if plainButton.isSelected {
// 設置選中狀態的圖片和背景顏色
config?.image = UIImage(systemName: "paperplane.fill")?.withTintColor(.white, renderingMode: .alwaysOriginal)
config?.background.backgroundColor = .systemMint
} else {
// 設置正常狀態的圖片和背景顏色
config?.image = UIImage(systemName: "paperplane")?.withTintColor(.systemMint, renderingMode: .alwaysOriginal)
config?.background.backgroundColor = .white
}
plainButton.configuration = config
}
@objc func click() {
plainButton.isSelected.toggle()
updateButtonConfiguration()
}
快樂改按鈕😎