SwiftUI 中级之List显示Sqlite数据库内容(2020年教程)
数据介绍
我们手动创建一个landmark.db 文件,其包含一个landmark表。表内容如下图
csv文件
id,name,imageName
1001,Turtle Rock,turtlerock
1002,Silver Salmon Creek,silversalmoncreek
1003,Chilkoot Trail,chilkoottrail
1004,St. Mary Lake,stmarylake
1005,Twin Lake,twinlake
属性
- 纯Swift代码
- 可以自定义table名称
- 使用SwiftUI进行显示
使用方法
- 如何加入到你到项目
(1) copy file to your project
SQLiteBbase.swift
SQLiteDB.swift
SQLTable
- 初始化
add init code to AppDelegate.swfit
let db = SQLiteDB.shared
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
db.DB_NAME="landmarkdemo.db"
_ = db.open(copyFile:true)
return true
}
- create class
if you want to custom table name,you can set custom name with the following code
static func customTables() ->String {
return "landmark"
}
if you want to use class name as table name ,you need use the following code
static func customTables() ->String {
return ""
}
class code
import Foundation
import SwiftUI
class SQLandmark: SQLTable {
var id = -1
var name = ""
var imageName = ""
override var description:String {
return "id: \(id), name: \(name)"
}
static func customTables() ->String {
return "landmark"
}
}
extension SQLandmark {
var image: Image {
ImageStore.shared.image(name: imageName)
}
}
4、 create data.swift to init data
import Foundation
import SwiftUI
let sqLandmarkData: [SQLandmark] = SQLandmark.rows(order:"id ASC")
5、 create UI by SwiftUI
import SwiftUI
struct ListSqliteView: View {
var body: some View {
NavigationView {
List{
ForEach(sqLandmarkData,id:\.self){ item in
//Text(item.name)
SQLMRow(landmark: item)
}
.navigationBarTitle(Text("Landmarks"))
}
}
}
}
import SwiftUI
struct SQLMRow: View {
var landmark: SQLandmark
var body: some View {
HStack {
landmark.image
.resizable()
.frame(width: 50, height: 50)
Text(landmark.name)
Spacer()
}
}
}
效果
项目全部代码
https://github.com/zhishidapang/SwiftUISqliteORM
更多SwiftUI教程和代码关注专栏
- 请关注我的专栏 SwiftUI教程与源码
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。