SwiftUI - Form控件

Form

A container for grouping controls used for data entry, such as in settings or inspectors

SwiftUI gives us a dedicated view type for this purpose, called Form. Forms are scrolling lists of static controls like text and images, but can also include user interactive controls like text fields, toggle switches, buttons, and more.

Declaration

struct Form<Content> where Content : View

Overview

SwiftUI applies platform-appropriate styling to views contained inside a form, to group them together. Form-specific styling applies to things like buttons, toggles, labels, lists, and more. Keep in mind that these stylings may be platform-specific. For example, forms apppear as grouped lists on iOS, and as aligned vertical stacks on macOS.

The following example shows a simple data entry form on iOS, grouped into two sections. The supporting types (NotifyMeAboutType and ProfileImageSize) and state variables (notifyMeAbout, profileImageSize, playNotificationSounds, and sendReadReceipts) are omitted for simplicity.

var body: some View {
    NavigationView {
        Form {
            Section(header: Text("Notifications")) {
                Picker("Notify Me About", selection: $notifyMeAbout) {
                    Text("Direct Messages").tag(NotifyMeAboutType.directMessages)
                    Text("Mentions").tag(NotifyMeAboutType.mentions)
                    Text("Anything").tag(NotifyMeAboutType.anything)
                }
                Toggle("Play notification sounds", isOn: $playNotificationSounds)
                Toggle("Send read receipts", isOn: $sendReadReceipts)
            }
            Section(header: Text("User Profiles")) {
                Picker("Profile Image Size", selection: $profileImageSize) {
                    Text("Large").tag(ProfileImageSize.large)
                    Text("Medium").tag(ProfileImageSize.medium)
                    Text("Small").tag(ProfileImageSize.small)
                }
                Button("Clear Image Cache") {}
            }
        }
    }
}
截屏2021-09-27 上午8.56.51.png

Creating a Form

init(content: () -> Content)

Simple Example

1、 Form包含一个Text,可滚动

// 定义结构体ContentView,遵守View协议
struct ContentView: View {
    //  定义计算属性body
    // some View:表示返回的内容将遵守View协议
    var body: some View {
        // 返回一个具体类型的View
        Form {
            Text("Hello, World!")
        }
    }
}

效果:

form1.png

2、包含多个Text,但是最多10控件

struct ContentView: View {
    var body: some View {
        Form {
            Text("Hello, World!")
            Text("Hello, World!")
            Text("Hello, World!")
            Text("Hello, World!")
            Text("Hello, World!")
        }
    }
}
form2.png

3、要想使用多个,可以使用Group进行分组,界面UI效果不变

struct ContentView: View {
    var body: some View {
        Form {
            Group {
                Text("Hello, World!")
                Text("Hello, World!")
                Text("Hello, World!")
            }
            Group {
                Text("Hello, World!")
                Text("Hello, World!")
                Text("Hello, World!")
            }
        }
    }
}

4、如果想明显看到区分群组,可以使用Section

struct ContentView: View {
    var body: some View {
        Form {
            Section {
                Text("Hello, World!")
                Text("Hello, World!")
                Text("Hello, World!")
            }
            Section {
                Text("Hello, World!")
                Text("Hello, World!")
                Text("Hello, World!")
            }
        }
    }
}
form3.png

设置header和footer视图

struct ContentView: View {
    var body: some View {
        Form {
            Section(header: Text("Section 1")) {
                Text("Hello, World!")
                Text("Hello, World!")
                Text("Hello, World!")
            }


            Section(header: Text("Section 2")) {
                ForEach(0..<5) {
                    Text("Dynamic row \($0)")
                }
            }

            Section(header: Text("Section 3"), footer: Text("Section 3 footer")) {
                Text("Static row")
                Text("Static row")
            }
        }
    }
}
form5.png

5、使用ForEach循环创建view

struct ContentView: View {
    var body: some View {
        Form {
            ForEach(0..<100) {
              Text("Row: \($0)")
            }
        }
    }
}
form4.png

6、通过NavigationView和Form布局一个简单的设置界面

struct ContentView: View {
    // 用户名
    @State var username: String = ""
    @State var isPrivate: Bool = true
    @State var notificationsEnabled: Bool = false
    @State private var previewIndex = 0
    var previewOptions = ["Always","When Unlocked", "Never"]

    var body: some View {
        NavigationView {
            Form {
                Section(header: Text("PROFILE")) {
                    TextField("Username", text: $username)
                    Toggle(isOn: $isPrivate) {
                        Text("Private Account")
                    }
                }

                Section(header: Text("NOTIFICATIONS")) {
                    Toggle(isOn: $notificationsEnabled) {
                        Text("Enabled")
                    }
                    Picker(selection: $previewIndex, label: Text("Show Previews")) {
                        ForEach(0 ..< previewOptions.count) {
                            Text(self.previewOptions[$0])
                        }
                    }
                }

                Section(header: Text("ABOUT")) {
                    HStack {
                        Text("Version")
                        Spacer()
                        Text("2.2.1")
                    }
                }

                Section {
                    Button(action: {
                        print("Perform an action here...")
                    }) {
                        Text("Reset All Settings")
                    }
                }
            }
            .navigationBarTitle("Settings")
        }
    }
}
Simulator Screen Shot - iPhone 12 - 2021-09-27 at 09.05.57.png

具体详情可查看SwiftUI Form tutorial – how to create and use Form in SwiftUI

如果要去除两边间距,可以将From改为List,并添加listStyle

struct ContentView: View {
    // 用户名
    @State var username: String = ""
    @State var isPrivate: Bool = true
    @State var notificationsEnabled: Bool = false
    @State private var previewIndex = 0
    var previewOptions = ["Always","When Unlocked", "Never"]

    var body: some View {
        NavigationView {
            List {
                Section(header: Text("PROFILE")) {
                    TextField("Username", text: $username)
                    Toggle(isOn: $isPrivate) {
                        Text("Private Account")
                    }
                }

                Section(header: Text("NOTIFICATIONS")) {
                    Toggle(isOn: $notificationsEnabled) {
                        Text("Enabled")
                    }
                    Picker(selection: $previewIndex, label: Text("Show Previews")) {
                        ForEach(0 ..< previewOptions.count) {
                            Text(self.previewOptions[$0])
                        }
                    }
                }

                Section(header: Text("ABOUT")) {
                    HStack {
                        Text("Version")
                        Spacer()
                        Text("2.2.1")
                    }
                }

                Section {
                    Button(action: {
                        print("Perform an action here...")
                    }) {
                        Text("Reset All Settings")
                    }
                }
            }.listStyle(GroupedListStyle()).navigationBarTitle("Settings")
        }
    }
}
form6.png

参考

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • A collection of awesome browser-side JavaScript[https://d...
    Feng_Du阅读 1,017评论 0 1
  • 注:该篇文章摘自于github.com/vhf/free-programming-books,英文版。访问该项目获...
    stuha阅读 4,049评论 0 13
  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,486评论 0 10
  • 我是黑夜里大雨纷飞的人啊 1 “又到一年六月,有人笑有人哭,有人欢乐有人忧愁,有人惊喜有人失落,有的觉得收获满满有...
    陌忘宇阅读 8,610评论 28 53
  • 首先介绍下自己的背景: 我11年左右入市到现在,也差不多有4年时间,看过一些关于股票投资的书籍,对于巴菲特等股神的...
    瞎投资阅读 5,792评论 3 8