SwiftUI 中級之List顯示Sqlite數據庫內容(2020年教程)

SwiftUI 中級之List顯示Sqlite數據庫內容(2020年教程)

數據介紹

咱們手動建立一個landmark.db 文件,其包含一個landmark表。表內容以下圖
SwiftUI 中級之List顯示Sqlite數據庫內容git

csv文件github

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. 如何加入到你到項目

(1) copy file to your project數據庫

SQLiteBbase.swift
SQLiteDB.swift
SQLTable
  1. 初始化

add init code to AppDelegate.swfitswift

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
    }
  1. create class

if you want to custom table name,you can set custom name with the following codeapp

static func customTables() ->String {
        return "landmark"
    }

if you want to use class name as table name ,you need use the following codeide

static func customTables() ->String {
        return ""
    }

class codespa

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)
    }
}

四、 create data.swift to init datacode

import Foundation
import SwiftUI

let sqLandmarkData: [SQLandmark] = SQLandmark.rows(order:"id ASC")

五、 create UI by SwiftUIblog

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()
        }
    }
}

效果

SwiftUI 中級之List顯示Sqlite數據庫內容

項目所有代碼

https://github.com/zhishidapang/SwiftUISqliteORM教程

更多SwiftUI教程和代碼關注專欄

相關文章
相關標籤/搜索