這個問題在這里已經有了答案:
但奇怪的是,如果我使用,background(Color.red)那么我的按鈕輸出看起來像這樣(第 39 行)。
![SwiftUI 中的“.colorName”和“Color.colorName”有什么區別?如果它們相同,為什么會顯示兩個輸出?[復制]](https://img.uj5u.com/2021/11/29/633e459a35f24001a78b48b469fa6071.jpg)
現在我的問題是
- 為什么有兩個不同的輸出?
Color.red和之間的實際區別是.red什么?- 何時使用
Color.red和.red?
完整代碼如下
使用.red代碼
//
// ContentView.swift
// Dicey-SwiftUI
//
// Created by Moh. Absar Rahman on 26/11/21.
//
import SwiftUI
struct ContentView: View {
@State var leftDiceNumber = 1
@State var rightDiceNumber = 1
var body: some View {
ZStack {
Image("background")
.resizable()
.edgesIgnoringSafeArea(.all)
VStack {
Image("diceeLogo")
Spacer()
HStack {
DiceView(n: leftDiceNumber)
DiceView(n: rightDiceNumber)
}
.padding(.horizontal)
Spacer()
Button(action: {
leftDiceNumber = 2
rightDiceNumber = 2
}) {
Text("Roll")
.font(.system(size: 50))
.fontWeight(.heavy)
.foregroundColor(.white)
.padding(.horizontal)
}
.background(.red)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct DiceView: View {
let n: Int
var body: some View {
Image("dice\(n)")
.resizable()
.aspectRatio(1, contentMode: .fit)
.padding()
}
}
使用Color.red代碼
//
// ContentView.swift
// Dicey-SwiftUI
//
// Created by Moh. Absar Rahman on 26/11/21.
//
import SwiftUI
struct ContentView: View {
@State var leftDiceNumber = 1
@State var rightDiceNumber = 1
var body: some View {
ZStack {
Image("background")
.resizable()
.edgesIgnoringSafeArea(.all)
VStack {
Image("diceeLogo")
Spacer()
HStack {
DiceView(n: leftDiceNumber)
DiceView(n: rightDiceNumber)
}
.padding(.horizontal)
Spacer()
Button(action: {
leftDiceNumber = 2
rightDiceNumber = 2
}) {
Text("Roll")
.font(.system(size: 50))
.fontWeight(.heavy)
.foregroundColor(.white)
.padding(.horizontal)
}
.background(Color.red)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct DiceView: View {
let n: Int
var body: some View {
Image("dice\(n)")
.resizable()
.aspectRatio(1, contentMode: .fit)
.padding()
}
}
注意:請不要嘲笑我。我還是個初學者,正在努力學習SwiftUI
uj5u.com熱心網友回復:
這稱為隱式成員運算式。在可以從其他資訊(如回傳型別)推斷型別的情況下,可以省略實際的型別名稱。
在
.background(Color.red)
它不能被省略,因為引數不是輸入的Color,而是some View. red如果型別丟失,它不知道去哪里尋找。
代碼無法解釋您在預覽中看到的差異,因此我建議您在設備上執行它,因為它可能是一些不需要的人工制品。我在當前的 Xcode 版本中看到了很多。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/368986.html
