我是 SwiftUI 和 Xcode 13.2 的新用戶。我正在學習關于 Udemy 的課程,但是當出現“無法為運算式生成診斷;請提交錯誤報告 ( https://swift.org/contributing/#reporting-bugs ) 和包括專案”。就在網上說的 var body: some View {}。這是整個代碼。
import SwiftUI
struct ContentView: View {
@State var userText:String = ""
@State var mode:Int = 1
var body: some View {
VStack {
if mode == 1 {
Text(userText.capitalized())
.font(.largeTitle)
} else if mode == 2 {
Text(userText.lowercased())
.font(.largeTitle)
} else {
Text(userText.uppercased())
.font(.largeTitle)
}
}
TextField("Enter text here...", text: $userText)
.background(Color.yellow)
.padding()
Text(userText)
.font(.largeTitle)
HStack{
Button(action: {mode = 1}) {
RoundedButton(text: "Capitalize", color: .green)
.padding(5)
}
Button(action: {mode = 2}) {
RoundedButton(text: "Lower", color: .blue)
}
Button(action: {mode = 3}) {
RoundedButton(text: "All Caps", color: .red)
.padding(5)
}
}
}
}
struct RoundedButton: View {
var text:String
var color:Color
var body: some View {
Text(text)
.bold()
.frame(maxWidth:.infinity)
.padding()
.background(color)
.foregroundColor(.black)
.cornerRadius(10)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.previewInterfaceOrientation(.portrait)
}
}
我該如何解決?
uj5u.com熱心網友回復:
該問題與您在第一個if條件中發現的條件有關。
Text(userText.capitalized())
SwiftUI 不喜歡使用 .capitalized()
在您的第三種情況下,您正在使用.uppercased(). 也許這就是你打算使用的?
要回答這個問題,解決這個問題的方法是洗掉 .capitalized()
uj5u.com熱心網友回復:
該函式capitalized()是swift中不存在的函式。但是,capitalized(with locale: Locale?)請參閱此檔案
https://developer.apple.com/documentation/foundation/nsstring/1414023-capitalized
進行解釋。
要將字串大寫,可以使用方法capitalized,例如theString.capitalized. 沒有結局()。
所以你得到的錯誤是由于使用了一個不存在的函式。替換 capitalized()為capitalized,這將解決您的錯誤。
在您的代碼中,使用以下內容來修復您的錯誤并在文本中大寫您的字串:
Text(userText.capitalized)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/407140.html
標籤:
