11

我尝试了 swiftUI 教程“处理用户输入”。

https://developer.apple.com/tutorials/swiftui/handling-user-input

使用“For”而不是“For Each”实现。但出现错误“包含控制流语句的闭包不能与函数构建器'ViewBuilder'一起使用”。

我该怎么做?

从:

import SwiftUI

struct LandmarkList: View {
    @State var showFavoritesOnly = true
    
    var body: some View {
        NavigationView{
            List{
                Toggle(isOn: $showFavoritesOnly){
                    Text("Show FavatiteOnly")
                }
                
                ForEach(landmarkData) { landmark in
                    if !self.showFavoritesOnly || landmark.isFavorite {
                            NavigationLink(destination: LandmarkDetail(landmark: landmark)) {
                                LandmarkRow(landmark: landmark)
                            }
                        }
                }
            }
            .navigationBarTitle(Text("Landmarks"))
        }
    }
}

至(我写):

import SwiftUI

struct LandmarkList: View {
    @State var showFavoritesOnly = true
    
    var body: some View {
        NavigationView{
            List{
                Toggle(isOn: $showFavoritesOnly){
                    Text("Show FavatiteOnly")
                }
                
                for landmark in landmarkData {
                    if $showFavoritesOnly || landmark.isFavorite {
                        NavigationLink(destination: LandmarkDetail(landmark: landmark)){
                            LandmarkRow(landmark: landmark)}
                        }
                }
            }
            .navigationBarTitle(Text("Landmarks"))
        }
    }
}
4

0 回答 0