我想以與按鈕已經存在的類似方式實作文本的修飾符設定。
又名:
Button( ... )
.buttonStyle(.plain) // <-- .plain and not PlainStyle()
問題
當然,我不能使用不完全一樣的不透明。如果是 aView我可以將它包裝在 anAnyView但對于ViewModifiers 我需要另一個解決方案。
錯誤:函式宣告了一個不透明的回傳型別,但其主體中的回傳陳述句沒有匹配的底層型別
也許擁有類似修飾符的東西是一個額外的想法,.textStyle(.title)但在我看來,它可以大大減少我撰寫的代碼。
資源
struct TitleStyle: ViewModifier {
func body(content: Content) -> some View {
...
}
}
struct BodyStyle: ViewModifier {
func body(content: Content) -> some View {
...
}
}
enum TextStyle {
case title
case body
// Error: Function declares an opaque return type,
// but the return statements in its body do not have matching underlying types
var modifier: some ViewModifier {
switch self
{
case .title: return TitleStyle()
case .body: return BodyStyle()
}
}
}
uj5u.com熱心網友回復:
它的作業方式不同。由于所有這些都圍繞泛型,我們需要限制已知具體型別的宣告。
所以,有了宣告TitleStyle和BodyStyle具體,我們可以指定
extension ViewModifier where Self == TitleStyle {
static var title: TitleStyle { TitleStyle() }
}
extension ViewModifier where Self == BodyStyle {
static var body: BodyStyle { BodyStyle() }
}
然后宣告擴展以在上面使用,如
extension View {
func textStyle<Style: ViewModifier>(_ style: Style) -> some View {
ModifiedContent(content: self, modifier: style)
}
}
所以我們可以做演示
struct Demo_Previews: PreviewProvider {
static var previews: some View {
Text("Demo")
.textStyle(.title)
}
}

使用 Xcode 13.4 / iOS 15.5 準備
GitHub 中的測驗模塊
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/491675.html
標籤:IOS 迅速 迅捷 伊帕多斯 swiftui-文本
