🚫view.foreground()
此文作廢 ❗️
定義
swift⟩ custom ⟩ extension ⟩ View ⟩ .foreground()
此文作廢。請用: view.foregroundStyle()❗️
import SwiftUI
// ⭐️ 此擴充可用任何的 View 當前景,不只是漸層顏色而已。
extension View {
/// ⭐️ 用法:view.foreground(_:)
/// 應用:
/// 1. 將文字塗上漸層顏色:「text.foreground(gradient)」
public func foreground<Overlay: View>(_ overlay: Overlay) -> some View {
self // ⭐️ 先設好 self 的 frame
.overlay(overlay) // ⭐️ 將 overlay 貼上去
.mask(self) // ⭐️ 裁掉 self 以外的地方
}
}依照定義,我們只能設定 Color 型別的前景色:
func foregroundColor(_ color: Color?) -> some View但這裡的自訂擴充可以超越這個限制。
重要概念
.foregroundColor 的設定牽涉到 view hierarchy 的概念,有點像 CSS (Cascading Style Sheet) 一樣,不管是母視件 (parent view) 還是子視件 (child view),都可以設定 .foregroundColor。如果母視件做了設定,則這些設定也會「同時套用到子視件」上面。
但有一點要注意:如果子視件 (較內層的 view) 另外設定了 .foregroundColor,則母視件的設定會直接被忽略喔! 👉 舉例:How does SwiftUI decide which part is foreground? - StackOverflow

.foregroundColor() 只能讓我們設定「前景色」,如果要套用諸如漸層這些比較花俏的東西時,就不行。因此,下面我們自己開發可以套用「任何 View」到前景的 extension。

import SwiftUI
import PlaygroundSupport
struct ContentView: View {
var body: some View {
Text("SwiftUI is awesome!")
.font(.largeTitle)
.foreground(Gradient.horizontal(.red, .orange))
}
}
PlaygroundPage.current.setLiveView(ContentView())Gradient.horizontal() #todo
Gradient as foreground color of Text in SwiftUI - StackOverflow
Gradient in SwiftUI - Sarun
參考資料
Last updated
Was this helpful?