弹出Sheet视图 - MVVM模式
=======================
## 知识点
* 采用MVVM模式, 循环数据并弹出Sheet视图
## 实战演习
### AppData.swift
~~~swift
////////////////////////////////////
// 弹出Sheet视图 - MVVM模式
//
// 小马视频频道
// http://komavideo.com
////////////////////////////////////
import SwiftUI
struct Hero {
var name: String
var showname: String
var attack: Int
}
struct HeroViewModel: Identifiable {
var id = UUID()
var hero: Hero
var desc: String {
return "英文名:" + hero.name + "/攻击力:\(hero.attack)"
}
}
class AppData: ObservableObject {
@Published var heroes: [HeroViewModel]
init() {
self.heroes = [
HeroViewModel(hero: Hero(name: "8bit", showname: "8比特", attack: 5)),
HeroViewModel(hero: Hero(name: "barley", showname: "巴里", attack: 3)),
HeroViewModel(hero: Hero(name: "bea", showname: "蜜蜂", attack: 5)),
HeroViewModel(hero: Hero(name: "bibi", showname: "芘芘", attack: 4)),
]
}
}
~~~
### ContentView.swift
~~~swift
import SwiftUI
struct HeroView: View {
@Environment(\.presentationMode) var presentation
let herovm: HeroViewModel
var body: some View {
VStack {
Spacer()
Text(herovm.hero.showname)
.font(.largeTitle)
Image(herovm.hero.name)
.resizable()
.frame(width: 330, height: 250)
.cornerRadius(20)
Text(herovm.desc)
Spacer()
Button("关闭") {
self.presentation.wrappedValue.dismiss()
}.font(.title)
}
}
}
struct ContentView: View {
@EnvironmentObject var appData: AppData
@State private var openSheet: HeroViewModel? = nil
var body: some View {
List {
ForEach(self.appData.heroes) { vm in
HStack {
Image(vm.hero.name)
.resizable()
.frame(width: 50, height: 50)
.cornerRadius(15)
Button(action: {
self.openSheet = vm
}, label: {
Text(vm.hero.showname)
})
}
}
}
.sheet(item: self.$openSheet) { vm in
HeroView(herovm: vm)
}
}
}
~~~
### myappApp.swift
```swift
import SwiftUI
@main
struct myappApp: App {
@StateObject var appData: AppData = AppData()
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(self.appData)
}
}
}
```
## 课程文件
https://github.com/komavideo/LearnSwiftUI
## 小马视频频道
http://komavideo.com
没有合适的资源?快使用搜索试试~ 我知道了~
资源推荐
资源详情
资源评论
收起资源包目录
SwiftUI iOS 开发入门教学.zip (28个子文件)
LearnSwiftUI-master
Lesson21
README.md 3KB
Lesson17
README.md 1KB
Lesson14
README.md 1KB
Lesson18
README.md 1KB
Lesson11
README.md 1KB
Lesson26
README.md 859B
Lesson02
README.md 1KB
Lesson01
README.md 1019B
Lesson22
README.md 1KB
Lesson10
README.md 2KB
Lesson15
README.md 1KB
Lesson19
README.md 1KB
Lesson06
README.md 1001B
Lesson20
README.md 1KB
Lesson27
README.md 2KB
Lesson04
README.md 1KB
Lesson24
README.md 2KB
Lesson25
README.md 2KB
Lesson08
README.md 1KB
Lesson23
README.md 957B
Lesson09
mvvm-pattern.png 12KB
README.md 1KB
Lesson07
README.md 2KB
Lesson05
README.md 1KB
Lesson16
README.md 2KB
Lesson13
README.md 2KB
Lesson03
README.md 1017B
Lesson12
README.md 2KB
共 28 条
- 1
资源评论
博士僧小星
- 粉丝: 1768
- 资源: 5875
下载权益
C知道特权
VIP文章
课程特权
开通VIP
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功