ios - 使用按钮快速循环遍历数组项

标签 ios arrays swift

我对编码相当陌生,所以如果这是一个愚蠢的问题,我深表歉意,但我正在创建一个应用程序,它将(按一下按钮)在标签上显示数组的第一项,然后如果我再次按下该按钮,它将显示第二项,然后如果您再次按下它,则会显示第三项,依此类推。现在我所能做的就是让我的应用程序从数组中选择一个随机项目,然后显示它。

如果您能提供帮助,非常感谢!

这是我的代码:

let prompts = ["A", "B","C","D","E","F","G","H"]

    @IBOutlet var PromptLbl: UILabel!


    @IBAction func GivePrompt(_ sender: UIButton)
    {
        let selected = Int (arc4random()) % 8
        PromptLbl.text = (prompts[selected])
    }

最佳答案

只需声明一个变量并在单击按钮时不断更新其值+1。

let prompts = ["A", "B","C","D","E","F","G","H"]
var currentIndexCount = 0 
@IBOutlet var PromptLbl: UILabel!


@IBAction func GivePrompt(_ sender: UIButton)
{
 if currentIndexCount < prompts.count {
  PromptLbl.text = prompts[currentIndexCount]
  currentIndexCount = currentIndexCount + 1
 }
}

关于ios - 使用按钮快速循环遍历数组项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58986801/

相关文章:

ios - 如何使用 swift 3 正确表达此 'rangeOfCharacter' 语句?

ios - Swift:将数据从 UITableView 发送到 UIViewController

java - 是否可以将字符串数组放入缓冲的阅读器中?

ios - 单击表格 View 单元格行时如何推送新的 View Controller ?

swift - 尝试通过 Swift 克隆 git 存储库遇到协议(protocol)冲突

ios - 自调整单元格不适用于图像

ios - 沿弧线放置 UICollectionViewCells (UIBezierPath)

javascript - 循环从二维数组创建对象键和值

python - Pandas df.to_records() 返回一维 numpy 数组

ios - 重新加载表格 View 后出现抖动