gpt4 book ai didi

ios - Swift:如何增加数组中的元素

转载 作者:行者123 更新时间:2023-11-30 13:41:05 26 4
gpt4 key购买 nike

我尝试使用计时器在一段时间后在标签内显示不同的文本,但无法增加自定义类型数组的元素。

这是代码:

    import UIKit

class WorkWorkoutViewOne: UIViewController {

@IBOutlet weak var exerciseTitle: UILabel!
@IBOutlet weak var timerLabel: UILabel!
@IBOutlet weak var instructionsLabel: UILabel!
@IBOutlet weak var exerciseImage: UIImageView!


var counter = 15
var timer: NSTimer?

var workoutExercisesShuffled = [Exercise]()
override func viewDidLoad() {
super.viewDidLoad()

let image: UIImage = workoutExercisesShuffled[0].filename!
exerciseImage.image = image

let titleLabel = workoutExercisesShuffled[0].name
exerciseTitle.text = titleLabel

let instructionsTitle = workoutExercisesShuffled[0].instructions
instructionsLabel.text = instructionsTitle

var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "timerAction", userInfo: nil, repeats: true)
}

var timerTwo: NSTimer?
var counterTwo = 15

func timerAction() {
--counter
timerLabel.text = "\(counter)"
if (counter == 0) {
timer?.invalidate()
let image: UIImage = workoutExercisesShuffled[1].filename!
exerciseImage.image = image

let titleLabel = workoutExercisesShuffled[1].name
exerciseTitle.text = titleLabel

let instructionsTitle = workoutExercisesShuffled[1].instructions
instructionsLabel.text = instructionsTitle

timerLabel.text = "\(counterTwo)"

var timerTwo = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "timerActionTwo", userInfo: nil, repeats: true)

}
}

使用timerThree、timerFour等重复此方法似乎很笨拙且不必要,因此希望有一种方法来增加数组值,而不必在不同的函数中单独调用。

最佳答案

试试这个,它使用两个方法和一个索引。

工作流程

  • 最初,index 设置为 0,counter 设置为 15。
  • updateExercise() 被调用。

    • 更新了练习用户界面。
    • 如果index为0,则创建计时器
  • timerAction() 在计时器触发后调用。

    • 计数器递减并更新计数器标签。
    • 如果counter为0且index等于练习次数-1,则计时器无效。
    • 如果 counter 为 0 并且 index < number ofexercise -1 index 递增,counter 会重置到 15 并再次调用 updateExercise()
<小时/>
    var counter = 15
var index = 0

var timer: NSTimer?

var workoutExercisesShuffled = [Exercise]()

override func viewDidLoad() {
super.viewDidLoad()
updateExercise()
}

func updateExercise() {
let image: UIImage = workoutExercisesShuffled[index].filename!
exerciseImage.image = image

let titleLabel = workoutExercisesShuffled[index].name
exerciseTitle.text = titleLabel

let instructionsTitle = workoutExercisesShuffled[index].instructions
instructionsLabel.text = instructionsTitle

if index == 0 {
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "timerAction", userInfo: nil, repeats: true)
}
}

func timerAction() {
counter -= 1
timerLabel.text = "\(counter)"
if (counter == 0) {
if index == workoutExercisesShuffled.count - 1 {
timer!.invalidate()
timer = nil
} else {
index += 1
counter = 15
updateExercise()
}
}
}

关于ios - Swift:如何增加数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35555058/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com