限制列表的对象数量 - SwiftUi
Posted
技术标签:
【中文标题】限制列表的对象数量 - SwiftUi【英文标题】:Limit List's objects amount - SwiftUi 【发布时间】:2021-07-21 09:20:01 【问题描述】:我的 WatchOS 应用在 Core Data 上运行。那里有 2 个视图:
-
FirstView - 带有添加新目标和已添加目标列表的按钮的视图。
AddGoalView - 按添加新目标后出现。
我还添加了List
,因为我想在我的应用程序中使用.onDelete
。
我试图限制用户创建无限数量的目标。我想给一个添加最多 10 个目标的机会,然后 AddGoal 按钮变为禁用。你有什么建议吗?
第一次查看代码:
struct FirstView: View
@Environment(\.managedObjectContext) var context
@FetchRequest (
entity:NewGoal.entity(),
sortDescriptors:[NSSortDescriptor(keyPath: \NewGoal.dateAdded, ascending: false)],
animation: .easeInOut )
var results:FetchedResults<NewGoal>
var body: some View
VStack
VStack(alignment: .leading)
NavigationLink(
destination: AddGoalView(),
label:
Text("Set Money Goal"))
Text("10/10")
VStack(alignment: .leading)
List
ForEach(results) item in
NavigationLink(
destination: TABmodule(goalItem: item, GTitle: item.goalTitle ?? "", Sum: item.neededSum, summarize: item.yourSum),
label:
HStack
HStack(alignment: .center, spacing:0)
Text(String(item.indDatenum))
Text(item.pickedValueDateS ?? "")
VStack(alignment: .leading)
Text(item.goalTitle ?? "")
HStack(spacing: 0)
Text("$\(item.yourSum, specifier: "%.f")")
Text("/ $\(item.neededSum, specifier: "%.f")")
).clipShape(RoundedRectangle(cornerRadius: 9))
.onDelete(perform: deleteGoal2)
.listStyle(PlainListStyle())
func deleteGoal2(at offsets: IndexSet)
for index in offsets
let item = results[index]
context.delete(item)
do
try context.save()
catch let err
print(err.localizedDescription)
AddGoalView 上的 AddGoal 函数:
private func addGoal()
if index == 0
pickedValueDateS = "W"
pickedValueDateN = 7 * indexnum
pickedValueDateN1 = 7 * indexnum
else if index == 1
pickedValueDateS = "M"
pickedValueDateN = 30 * indexnum
pickedValueDateN1 = 30 * indexnum
else if index == 2
pickedValueDateS = "Y"
pickedValueDateN = 365 * indexnum
pickedValueDateN1 = 365 * indexnum
else
pickedValueDateS = "N/A"
pickedValueDateN = 1
let goal = NewGoal(context: context)
goal.goalTitle = goalTitle
goal.dateAdded = Date()
goal.neededSum = neededSum
goal.pickedValueDateS = pickedValueDateS
goal.allNewSum = allNewSum
goal.pickedValueDateN = Int64(pickedValueDateN)////ALL DAYS
goal.pickedValueDateN1 = Int64(pickedValueDateN1)////MINUS DAYS
goal.dayChange = Int64(daychange)
goal.indDate = Int64(index)
goal.indDatenum = Int64(indexnum)
do
try context.save()
presentationMode.wrappedValue.dismiss()
catch let err
print(err.localizedDescription)
【问题讨论】:
【参考方案1】:将此添加到您想要禁用的任何View
,例如NavigationLink
,这样用户就无法访问View
.disabled(results.count >= 10)
【讨论】:
以上是关于限制列表的对象数量 - SwiftUi的主要内容,如果未能解决你的问题,请参考以下文章