挑戰(zhàn)
嘗試以下方式擴(kuò)展之前的程序:
- 創(chuàng)建一個自定義ViewModifier(和附帶的
View擴(kuò)展名),使視圖具有適合于視圖的藍(lán)色大標(biāo)題。 - 返回項目1,如果用戶選擇了0%小費,使用條件修飾符將文本總數(shù)視圖更改為紅色。
- 返回猜旗項目2,并創(chuàng)建一個FlagImage()視圖,該視圖使用已經(jīng)有的修飾符來渲染一個旗幟。
代碼如下
struct TopTitle: ViewModifier {
var title: String
func body(content: Content) -> some View {
VStack(spacing: 10) {
Text(title)
.font(.largeTitle)
.foregroundColor(.blue)
content
}
}
}
extension View {
func topTitleStyle(with text: String) -> some View {
self.modifier(TopTitle(title: text))
}
}
.topTitleStyle(with: "My title")
var is0Percentage: Bool {
let tipSelection = Double(tipPercentages[tipPercentage])
if tipSelection == 0 {
return true
} else {
return false
}
}
Text("$\(totalAmount, specifier: "%.2f")")
.foregroundColor(is0Percentage ? .red : .primary)
struct FlagImage: View {
var name: String
var body: some View {
Image(name)
.renderingMode(.original)
.clipShape(Capsule())
.overlay(Capsule().stroke(Color.black, lineWidth: 1.0))
.shadow(color: .black, radius: 2)
}
}
FlagImage(name: countries[number])