【发布时间】:2019-12-26 17:24:59
【问题描述】:
我有一个应用程序,其中包含存储在 CoreData 中的玩家列表(最多 21 个)。当 ViewController 加载时,它会在主屏幕的按钮上显示玩家名称。
但是,我已经让用户能够删除播放器,因为 21 可能对于他们的设置来说太多了。所以他们删除了,这会按预期从 CoreData 中删除数据。
然后他们刷新 ViewController,我只想显示仍在 CoreData 中的玩家数量的按钮。
所以我使用了这个代码:-
func reset()
{
let ksPickButtons = view.subviews.filter{$0 is KSPickButton}
ksPickButtons.forEach{$0.removeFromSuperview()}
//sort the player list
allPlayers.sort()
playerNo = 0
//run 2 loops to display the buttons (21 of them)
for j in 0...2 {
for i in 0...6 {
//use the CLASS KSPIckButton to format the buttons
let buttonOne:UIButton = KSPickButton(frame: CGRect(x: (j + 1) * 35 + (j * 80), y: (i + 5) * 35 + buttonSet, width: 110, height: 30))
//Add the button to the storyboard
self.view.addSubview(buttonOne)
buttonOne.addTarget(self,
action: #selector(playerButtons),
for: .touchUpInside)
//assign the tag to the button
buttonOne.tag = playerNo
//Give the buttons the players names
buttonOne.setTitle(allPlayers[playerNo], for: .normal)
playerNo += 1
}
}
initStart()
}
但是这一行
buttonOne.setTitle(allPlayers[playerNo], for: .normal)
给我一个致命错误:“索引超出范围”,因为不再有 21 个项目,我的循环会将 playerNo 增加到 21。
我尝试了“IF”语句,但在编译时它们被忽略了,并且“索引超出范围”仍然会停止代码执行。
如何识别/停止/跳过错误,只显示按钮数量对应玩家数量?
谢谢
【问题讨论】:
-
allPlayers应该有3 * 7 = 21项。如果它没有21项目,那么你的整个逻辑就是错误的。你看错地方了。 -
为什么不遍历玩家数组而不是两个嵌套循环呢?这将彻底解决索引问题。