SwiftUI之List 和form(2020版)
VStack
import SwiftUI
struct ContentView: View {
var body: some View {
VStack{
ForEach(0..<5){ Text("\($0)").tag($0)}
}
}
}
效果
List
import SwiftUI
struct ContentView: View {
var body: some View {
List{
ForEach(0..<5){ Text("\($0)").tag($0)}
}
}
}
效果
List with header & footer
struct ContentView: View {
var body: some View {
List{
Section(header:Text("header here"),footer: Text("Footer here"))
{
ForEach(0..<10){ Text("\($0)").tag($0)}
}
}
.listStyle(GroupedListStyle())
}
}
效果
List & navigation
struct ContentView: View {
@State private var selectedSnackIndex = 0
let treats = Treat.demoTreats
var body: some View {
NavigationView{
Form {
Picker(selection:$selectedSnackIndex, label:Text("Snack Type")){
ForEach(0..<treats.count){
Text(self.treats[$0].name).tag($0)
}
}
}
.navigationBarTitle(Text("hello"))
}
}
}
Treat.swift
import SwiftUI
struct Treat: Identifiable {
var id = UUID()
var name: String
var imageName: String
var description: String
}
extension Treat {
static let demoTreats = [
Treat(name: "Fish Cakes", imageName: "FlyingFish", description: "Lots of fish, lots of cakes!"),
Treat(name: "Mice Cream", imageName: "MiceCream", description: "Every kitty's favorite flavored Ice Cream"),
Treat(name: "Croissant", imageName: "Croissant", description: "Seems like cats wouldn't like them, but they do!"),
Treat(name: "Pancakes", imageName: "PanCakes", description: "They're cakes, but in the shape of a pan")
]
}
效果
完成代码
struct ContentView: View {
@State private var selectedSnackIndex = 0
@State private var isOn = false
@State var textValue = ""
let treats = Treat.demoTreats
var body: some View {
NavigationView{
Form {
Section{
Picker(selection:$selectedSnackIndex, label:Text("Snack Type")){
ForEach(0..<treats.count){
Text(self.treats[$0].name).tag($0)
}
}
}
Section{
Toggle(isOn:$isOn){
Text("would you like extra Milk with the order ")
}
if isOn{
Text("Milke will cost an extra $0.99")
.foregroundColor(.gray)
.font(Font.system(size:12))
}
}
Section{
TextField("Special Request",text:$textValue)
}
Section{
Button(action:{
}){
HStack{
Image(systemName:"paperplane")
.foregroundColor(.blue)
Text("Place Order")
}
}
}
}
.navigationBarTitle(Text("hello"))
}
}
}
效果
推荐文章
CoreData篇
TextField篇
- 《SwiftUI 一篇文章全面掌握TextField文本框 (教程和全部源码)》
- 《SwiftUI实战之TextField风格自定义与formatters》
- 《SwiftUI实战之TextField如何给键盘增加个返回按钮(隐藏键盘)》
- 《SwiftUI 当键盘出现时避免TextField被遮挡自动向上移动》
- 《SwiftUI实战之TextField如何给键盘增加个返回按钮(隐藏键盘)》
JSON文件篇
技术交流
QQ:3365059189
SwiftUI技术交流QQ群:518696470