讓 Button & NavigationLink 的內容維持原來顏色的 PlainButtonStyle

當我們使用 SwiftUI 顯示 Button & NavigationLink 時,它們會將內容全都變成同一個顏色,提醒使用者它們是可以點選的特別元件,比方以下例子裡 Button & NavigationLink 的圖文都變成了像阿凡達的藍色。

Button

Button(action: {
print("陪你很久很久")
}) {
HStack {
Image("陪你很久很久")
Text("陪你很久很久")
}
}

NavigationLink

NavigationView {
NavigationLink(destination: Image("陪你很久很久")) {
HStack {
Image("陪你很久很久")
Text("陪你很久很久")
}
}
}

不過我們不一定希望它們變色,尤其是圖片變色後變成一整片的藍,完全看不出來是什麼東東。

修正的方法很簡單,只要在 Button & NavigationLink 上呼叫 buttonStyle,將 button 的樣式設為 PlainButtonStyle 即可。

Button

Button(action: {
print("陪你很久很久")
}) {
HStack {
Image("陪你很久很久")
Text("陪你很久很久")
}
}
.buttonStyle(PlainButtonStyle())

NavigationLink

NavigationView {
NavigationLink(destination: Image("陪你很久很久")) {
HStack {
Image("陪你很久很久")
Text("陪你很久很久")
}
}
.buttonStyle(PlainButtonStyle())}

ps: 如果想讓 button 的圖片顯示原來的顏色,我們也可以從 image 呼叫 renderingMode,傳入 .original 讓圖片維持原本的顏色。

Button(action: {
print("陪你很久很久")
}) {
Image("陪你很久很久")
.renderingMode(.original)
}

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

彼得潘和學生們在開發 iOS App 路上曾經解決的問題集

彼得潘的 iOS App Neverland

Written by

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

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

彼得潘和學生們在開發 iOS App 路上曾經解決的問題集

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade