在数组上使用ScrollView的问题

时间:2020-08-09 09:09:52

标签: ios swift swiftui swiftui-scrollview

每当通过调用Web服务更新数组时,我都试图使用数组来显示一些游戏信息。数组填充良好,但是在运行时我得到:

通用结构'ForEachWithIndex'要求'Binding <[MatchData]>' 符合“ RandomAccessCollection”

我的ScrollView:

ScrollView{
    ForEach(GameCenterHelper.helper.$MatchList, id: \.self) {row  in
           ext("\(row.id)")
    }
}

我对数组的声明:

@State var MatchList: [MatchData] = [MatchData]()

和MatchData:

class MatchData : Identifiable {
    
var id: String

var LocalPlayer: Player
var RemotePlayer: Player

init(_ match: GKTurnBasedMatch) {
    
    let local = match.participants[0].player!
    let remote = match.participants[1].player ?? GKPlayer()
    self.id = match.matchID
    
    LocalPlayer = Player(Alias: local.alias
        , DisplayName: local.displayName
        , TeamPlayerId: local.teamPlayerID
        , PlayerId: local.gamePlayerID
    )
    
    RemotePlayer = Player(Alias: remote.alias
        , DisplayName: remote.displayName
        , TeamPlayerId: remote.teamPlayerID
        , PlayerId: remote.gamePlayerID
        
    )
}
}

我必须承认,这是我第一次使用状态来尝试刷新ScrollView,但是我发现它比我想象的要难得多,而且我不确定代码中出了什么问题。< / p>

1 个答案:

答案 0 :(得分:0)

您无需绑定即可迭代MatchList中的ForEach,直接访问

ScrollView{
    ForEach(GameCenterHelper.helper.MatchList, id: \.self) {row  in // << no $
           ext("\(row.id)")
    }
}