Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> iOS

วิธีรันงานซ้ำทุกช่วงเวลาที่กำหนดใน iOS ด้วย Timer

Apple มีคลาส Timer สำหรับรันงานหลังจากเวลาผ่านไป อ่านเอกสาร

จะสร้างแอปตัวอย่างพิมพ์ "hello" ทุก 5 วินาที

ขั้นตอนที่ 1: สร้างโปรเจกต์

Xcode → New Project → Single View Application → ชื่อ "HelloTutorialsPoint"

ขั้นตอนที่ 2: สร้างเมธอด doSomething

ใน ViewController.swift ใต้ viewDidLoad:

private func doSomething() {
let timer = Timer.scheduledTimer(timeInterval: 5.0, target: self,
selector: #selector(ViewController.hello), userInfo: nil, repeats: true)
}

ขั้นตอนที่ 3: สร้าง Selector และเรียกใช้

@objc func hello() {
print("hello")
}

เรียก doSomething() ใน viewDidLoad

โค้ดเต็ม

import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
override func viewDidLoad() {
super.viewDidLoad()
self.doSomething()
}
private func doSomething() {
let timer = Timer.scheduledTimer(timeInterval: 5.0, target: self,
selector: #selector(ViewController.hello), userInfo: nil, repeats: true)
}
@objc func hello() {
print("hello")
}
}

รันแอป ดู Console จะพบ "hello" พิมพ์ทุก 5 วินาที

วิธีรันงานซ้ำทุกช่วงเวลาที่กำหนดใน iOS ด้วย Timer