I'm studying Swift programing with using Apple official document "Develop in Swift Tutorial" https://developer.apple.com/tutorials/develop-in-swift/.
When I do that, I faced to some problems which I cannot resolve myself. So, could you help or advise me about it.
Problem:I can't implement this program which this below text say. How do I write the code??
(This section is that "Wrap-up: Lists and Text fields, Develop in Swift Tutorials")
Here's my current states...
import SwiftUI
struct ContentView: View {
@State private var names: [String] = []
@State private var nameToAdd = ""
@State private var pickedName = ""
@State private var shouldRemovePickedName = false
var body: some View {
VStack {
VStack(spacing: 8) {
Image(systemName: "person.3.sequence.fill")
.foregroundStyle(.tint)
.symbolRenderingMode(.hierarchical)
Text("Pick-a-Pal")
}
.font(.title)
.bold()
//3項条件演算子
Text(pickedName.isEmpty ? "" : pickedName)
.font(.title2)
.bold()
.foregroundStyle(.tint)
List {
ForEach(names, id: \.self) { name in
Text(name)
}
}
.clipShape(RoundedRectangle(cornerRadius: 8))
TextField("Add Name", text: $nameToAdd)
//単語の自動修正をオフにする
.autocorrectionDisabled()
.onSubmit {
if !nameToAdd.isEmpty {
names.append(nameToAdd)
nameToAdd = ""
}
}
Divider()
Toggle("Remove when picked", isOn: $shouldRemovePickedName)
Button {
if let randomName = names.randomElement() {
pickedName = randomName
if shouldRemovePickedName {
names.removeAll() { name in
return (name == randomName)
}
}
} else {
pickedName = ""
}
} label: {
Text("Pick Random Name")
.padding(.vertical, 8)
.padding(.horizontal, 16)
}
.buttonStyle(.borderedProminent)
.font(.title2)
}
.padding()
}
}
#Preview {
ContentView()
}