gpt4 book ai didi

swift - 使用计时器从 uitextfield 中放置的内容开始倒计时

转载 作者:行者123 更新时间:2023-11-30 10:29:34 25 4
gpt4 key购买 nike

下面的快速代码应该采用文本字段中放置的任何数字,然后按一秒倒计时。我不知道如何获取文本字段中的内容并对其进行倒数。不必担心确保用户在文本字段中放置的是数字而不是字符串。

    import UIKit

class ViewController: UIViewController {

var enterTime = UITextField()
var lblTime = UILabel()
var startBTN = UIButton()
var timer = Timer()
var counter = 33

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.

[enterTime,lblTime,startBTN].forEach{
$0.backgroundColor = .systemRed
view.addSubview($0)
$0.translatesAutoresizingMaskIntoConstraints = false
}

enterTime.frame = CGRect(x: view.center.x-115, y: view.center.y-200, width: 60, height: 50)
lblTime.frame = CGRect(x: view.center.x-115, y: view.center.y, width: 60, height: 50)
startBTN.frame = CGRect(x: view.center.x-115, y: view.center.y+200, width: 60, height: 50)

startBTN.addTarget(self, action: #selector(startHit), for: .touchDown)


}
@objc func startHit() {

timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)



}

@objc func timerAction() {



//This is where the user would take the time from uitextfield and causes it to count down
enterTime.text = counter

lblTime.text = "\(counter)"
}
}

最佳答案

1 ) 使计时器无效并使用 EnterTime 文本字段中的值启动计数器,并在 startHit 函数中启动计时器。

2 ) 在timerAction函数中,将计数器值减1并设置到lblTime中。

您可能需要如下修改 startHit 和 timerAction 函数。

@objc func startHit() {
timer.invalidate()
if let counterText = enterTime.text, let counterValue = Int(counterText) {
counter = counterValue
lblTime.text = String(counter)
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
}
}

@objc func timerAction() {
counter -= 1
lblTime.text = String(counter)
if ( counter == 0 ) {
timer.invalidate()
}
}

关于swift - 使用计时器从 uitextfield 中放置的内容开始倒计时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59433293/

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