SwiftUI 重新加载视图 [英] SwiftUI Reload View
问题描述
我有一个结构体,它可以从 CoreData 中混洗和列出记录.我想用按钮重新加载/刷新列表视图.我尝试使用 Button 中的函数.有没有办法做到这一点?
var body: some View {虚拟堆栈{列表 {ForEach(dictionary.shuffled().prefix(upTo: 10),id: \.self) { word in堆栈{Text("\(word.englishWord)").foregroundColor(Color.blue)Text("| \(word.urhoboWord) |").foregroundColor(Color.green)图像(字.图像名称).resizable().frame(宽:40,高:40)}//HStack}//ForEach 结束}//列表结束//按钮重新加载和洗牌列表按钮(动作:{}){文本(随机播放").填充().background(颜色.黑色).foregroundColor(Color.white).cornerRadius(6)}.navigationBarTitle(Text("Begin Learning"),displayMode: .inline)
你应该把这个 dictionary.shuffled().prefix(upTo: 10)
移到你的 ViewModel
并且您的视图只是根据数据重新加载.看看这个代码以供参考:
struct SampleShuffleView : 查看 {@ObservedObject var viewModel : ShuffleViewModel = ShuffleViewModel()var body : 一些视图{虚拟堆栈{List(self.viewModel.listData, id: \.self) { str in文本(字符串)}按钮(动作:self.shuffle){Text("Shuffle me").padding()}.background(Color.white).padding()}}功能洗牌(){self.viewModel.shuffle()}}类 ShuffleViewModel : ObservableObject {@Published var listData = [一"、二"、三"、四"]功能洗牌(){listData.shuffle()//或 listData = dictionary.shuffled().prefix(upTo: 10)}}
注意:当@ObservedObject
改变时,所有视图的组件都会被重新加载,所以考虑将较小的视图-视图模型分开,或者使用@State
变量.>
希望这会有所帮助.
I have a struct which shuffles and Lists records from CoreData. I would like to reload / Refresh the List view with a Button. I tried to use a function from within the Button. Is there a way I can do this?
var body: some View {
VStack {
List {
ForEach(dictionary.shuffled().prefix(upTo: 10),id: \.self) { word in
HStack {
Text("\(word.englishWord)")
.foregroundColor(Color.blue)
Text("| \(word.urhoboWord) |")
.foregroundColor(Color.green)
Image(word.imageName)
.resizable()
.frame(width:40, height: 40)
}//HStack
}//End of ForEach
}//End of List
//Button to reload and shuffle list
Button(action: {}) {
Text("Shuffle")
.padding()
.background(Color.black)
.foregroundColor(Color.white)
.cornerRadius(6)
}
.navigationBarTitle(Text("Begin Learning"),displayMode: .inline)
You should move this dictionary.shuffled().prefix(upTo: 10)
to your ViewModel
and your view just reload base on the data.
Take a look at this code for reference:
struct SampleShuffleView : View {
@ObservedObject var viewModel : ShuffleViewModel = ShuffleViewModel()
var body : some View {
VStack {
List(self.viewModel.listData, id: \.self) { str in
Text(str)
}
Button(action: self.shuffle) {
Text("Shuffle me").padding()
}.background(Color.white).padding()
}
}
func shuffle() {
self.viewModel.shuffle()
}
}
class ShuffleViewModel : ObservableObject {
@Published var listData = ["one", "two", "three", "four"]
func shuffle() {
listData.shuffle()
//or listData = dictionary.shuffled().prefix(upTo: 10)
}
}
Note: All view's components will be reloaded when @ObservedObject
changes, so consider to separate smaller view-viewmodel(s), or using @State
variable.
Hope this helps.
这篇关于SwiftUI 重新加载视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!