置頂
菜鳥入門,各位大佬輕噴,如有謬誤之處歡迎讨論建議,也歡迎各位道友與我同行
“不積跬步,無以至千裡;不積小流,無以成江海”
繼續
上文中已經實作了資料每一個 TODO 項的完成狀态切換、建立時間以及滑動删除功能。
同時完成一個資料的抽象,即将資料處理的部分抽象到一個對象内,頁面中隻管調用即可。
那麼本文中将實作将 TODO 項分組,已完成的 todo 和未完成的 todo 理應分開展示。
并且在 todo 項為空的時候進行提示。
根據這個分組,那麼我們可以将設定頁面做出來,類似于iOS原生的設定界面
最終效果如下:
實作
先對todo頁面進行修改
TodoView.swift
import SwiftUI
struct TodoView: View {
// 。。。省略參數定義部分
var body: some View {
VStack{
HStack{
// 頂部輸入框
}.padding()
// 如果有todo項的時候才顯示todo清單,否則提示沒有資料
if(todos.todoList.count > 0){
List{
Section("未完成", content: {
// 這裡使用 filter 把未完成的資料過濾出來
ForEach(todos.todoList.filter{(item)->Bool in
return item.isFinished == false;
}){ item in
HStack{
// 省略内部。。。
}.contentShape(Rectangle())
.onTapGesture {
todos.toggle(item: item)
}
}.onDelete{ IndexSet in // 這個調用将實作橫滑删除功能
todos.delete(offsets: IndexSet)
}
})
Section("已完成", content: {
// 這裡使用 filter 把已完成的資料過濾出來
ForEach(todos.todoList.filter{
(item) -> Bool in
return item.isFinished == true;
} ){ item in
HStack{
// 。。。 省略 todo 項内部
}.contentShape(Rectangle())
.onTapGesture {
todos.toggle(item: item)
}
}.onDelete{ IndexSet in
todos.delete(offsets: IndexSet)
}
})
}.animation(.default,value:todos.todoList)
}else{
Text("請添加TODO項").foregroundColor(.gray)
Spacer()
}
}
}
}
接下來以同樣的方式修改
SettingView.swift
import SwiftUI
struct SettingView: View {
@AppStorage("isLogin") private var isLogin:Bool = false;
@AppStorage("userName") private var userName:String = "";
var body:some View{
NavigationView{
if(isLogin){
List{
ForEach(0..<4){ item in
HStack{
Image(systemName: "person")
Text("使用者名")
Spacer()
Text(userName)
}
}
Section{
HStack{
Spacer()
Text("退出登陸").foregroundColor(.red)
Spacer()
}.onTapGesture {
isLogin = false;
}
}.navigationTitle("設定")
}
}else{
Text("請登入").foregroundColor(.red)
}
}
}
}
struct SettingView_Previews: PreviewProvider {
static var previews: some View {
SettingView()
}
}
總結
- Section 分組用在 List 元件中間,即将 List 從中間斷開。
- NavigationView 即一個有頭部的頁面,并且這個頁面的頭部會随着滑動到頂部變化樣式,還是挺友善的。
- 同時 NavigationView 也是另一種跳轉二級頁面的方式,并且頂部會帶有傳回按鈕。