由于 API 变动,此文章部分内容已失效,最新完整中文教程及代码请查看 https://github.com/WillieWangWei/SwiftUI-Tutorials
微信技术群
SwiftUI
代表未来构建 App 的方向,欢迎加群一起交流技术,解决问题。
加群现在需要申请了,可以先加我微信,备注 “SwiftUI”,我会拉你进群。
组合复杂界面
Landmarks
的主屏显示了一个滚动的分类列表,每个分类中都有水平滚动的地标标记。通过构建这样的主导航,我们来探究组合 view 是怎样适配不同设备大小和方向的。下载项目文件并按照以下步骤操作,也可以打开已完成的项目自行浏览代码。
- 预计完成时间:20 分钟
- 项目文件:下载
1. 添加 Home View
现在我们已经做好了 Landmarks
app 所需的所有 view,是时候给它们一个统一的 home view 了。 home view 不仅包含了所有其他 view,还提供了浏览和显示地标的方法。
1.1 在一个新文件 Home.swift
中创建一个自定义 view CategoryHome
。
Home.swift
import SwiftUI
struct CategoryHome: View {
var body: some View {
Text("Landmarks Content")
}
}
#if DEBUG
struct CategoryHome_Previews: PreviewProvider {
static var previews: some View {
CategoryHome()
}
}
#endif
1.2 修改 SceneDelegate
,把显示的地标列表换成 CategoryHome
view 。
SceneDelegate.swift
import SwiftUI
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Use a UIHostingController as window root view controller
let window = UIWindow(frame: UIScreen.main.bounds)
window.rootViewController = UIHostingController(rootView: CategoryHome().environmentObject(UserData()))
self.window = window
window.makeKeyAndVisible()
}
}
现在 home view 成了 Landmarks
app 的根,所系它需要一个方式去显示其他 view 。
1.3 在 Landmarks
中添加一个 NavigationView
来组织别的 view 。
我们在 app 中使用 NavigationView
和 NavigationButton
实例以及其他相关方法来构建分层导航结构。
Home.swift
import SwiftUI
struct CategoryHome: View {
var body: some View {
NavigationView {
Text("Landmarks Content")
}
}
}
#if DEBUG
struct CategoryHome_Previews: PreviewProvider {
static var previews: some View {
CategoryHome()
}
}
#endif
1.4 把导航栏设置成 Featured
。
Home.swift
import SwiftUI
struct CategoryHome: View {
var body: some View {
NavigationView {
Text("Landmarks Content")
.navigationBarTitle(Text("Featured"))
}
}
}
#if DEBUG
struct CategoryHome_Previews: PreviewProvider {
static var previews: some View {
CategoryHome()
}
}
#endif
2. 创建一个分类列表
Landmarks
app 以垂直的独立 row
显示所有分类,这给浏览提供了便利。我们可以通过组合垂直和水平 stacks
,并给列表添加滚动来完成此需求。
2.1 使用 Dictionary
结构的初始化方法 init(grouping:by:)
把地标组合到分类中,输入地标的 category
属性。
初始化项目文件给每个地标包含了预设的分类。
Home.swift
import SwiftUI
struct CategoryHome: View {
var categories: [String: