苹果iOS开发中用Swift如何写一个倒计时功能

本文首发于公众号“AntDream”,欢迎微信搜索“AntDream”或扫描文章底部二维码关注,和我一起每天进步一点点

在iOS开发中使用Swift实现一个倒计时功能比较常见,可以用于各种场景,例如倒计时按钮、显示倒计时时间等。下面展示一个简单的倒计时功能示例。

使用 Timer

最简单和直接的方式是使用 Timer 来实现倒计时功能。

1. 倒计时示例

下面是一个 CountdownTimer 类,可以在应用各种场景中进行倒计时。

import UIKit

class CountdownTimer {

    private var timer: Timer?
    private var totalTime: Int
    private var timeRemaining: Int
    private var onTick: ((Int) -> Void)?
    private var onCompletion: (() -> Void)?

    init(seconds: Int) {
        self.totalTime = seconds
        self.timeRemaining = seconds
    }

    func start(onTick: @escaping (Int) -> Void, onCompletion: @escaping () -> Void) {
        self.onTick = onTick
        self.onCompletion = onCompletion
        timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerTick), userInfo: nil, repeats: true)
    }

    func stop() {
        timer?.invalidate()
        timer = nil
    }

    @objc private func timerTick() {
        if timeRemaining > 0 {
            timeRemaining -= 1
            onTick?(timeRemaining)
        } else {
            timer?.invalidate()
            timer = nil
            onCompletion?()
        }
    }
}
2. 使用倒计时功能

现在我们创建一个简单的视图控制器来使用倒计时功能:

import UIKit

class CountdownViewController: UIViewController {

    private var countdownLabel: UILabel!
    private var startButton: UIButton!
    private var countdownTimer: CountdownTimer?

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

    private func setupUI() {
        view.backgroundColor = .white

        countdownLabel = UILabel()
        countdownLabel.text = "60"
        countdownLabel.font = UIFont.systemFont(ofSize: 48)
        countdownLabel.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(countdownLabel)

        startButton = UIButton(type: .system)
        startButton.setTitle("Start Countdown", for: .normal)
        startButton.addTarget(self, action: #selector(startCountdown), for: .touchUpInside)
        startButton.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(startButton)

        NSLayoutConstraint.activate([
            countdownLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            countdownLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor),

            startButton.topAnchor.constraint(equalTo: countdownLabel.bottomAnchor, constant: 20),
            startButton.centerXAnchor.constraint(equalTo: view.centerXAnchor)
        ])
    }

    @objc private func startCountdown() {
        countdownTimer?.stop()
        countdownTimer = CountdownTimer(seconds: 60)
        countdownTimer?.start(onTick: { [weak self] timeRemaining in
            self?.countdownLabel.text = "\(timeRemaining)"
        }, onCompletion: {
            print("Countdown completed!")
        })
    }
}

补充注意事项

1、 线程问题: 在实际应用中,确保 Timer 在主线程上操作 UI,否则需要使用 DispatchQueue.main.async 来确保在主线程上更新 UI。

2、 内存管理: 用 [weak self] 防止循环引用。

3、 暂停与继续: 如果需要实现倒计时的暂停和继续功能,需要额外管理时间状态,并在 Timer 重新启动时使用保存的时间。

4、 App 进入后台: 如果需要处理应用进入后台或者恢复前台,需要利用应用状态通知或 BackgroundTasks 来管理 Timer

通过这些步骤,有了基本的倒计时功能,您可以进一步根据具体需求进行扩展和定制。


欢迎关注我的公众号AntDream查看更多精彩文章!

AntDream

  • 8
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值