Swift: 遍历数组并逐项在屏幕上显示信息(屏幕更新)
Swift: Loop through an Array and present information on screen item by item (with screen updating)
我正在将信息存储在一个数组中,并希望将其一一呈现在屏幕上的UIButton/UILabel中等待时间为一秒。
当然,系统很聪明,会在更新屏幕之前计算出全部功能以节省资源...我怎样才能防止这种情况并在 运行 每个项目之后更新屏幕? (我使用的是 UIKit 而不是 SpriteKit)。
@objc private func infoButtonTapped(_ sender: Any) {
for item in Array {
statusButton.isHidden = true
updateScreen()
presentArray(item: item)
sleep(1)
}
}
func presentArray(item: ArrayItem) {
statusButton.isHidden = false
statusButton.titleLabel?.text = item.status
}
我试过了
view.setNeedsLayout()
并将特定部分设置为
DispatchQueue.main.async { xxx }
但这些技巧似乎都不起作用...
一个可能的解决方案是使用 scheduledTimer 更新您的按钮或标签,如下所示:
let sampleArray = [0,1,2,3,4,5,6,7,8,9,10]
var numberOfItem = 10
var sampleTimer:Timer!
override func viewDidLoad() {
super.viewDidLoad()
sampleTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(presentArray), userInfo: nil, repeats: true)
}
@objc func presentArray(){
if numberOfItem >= 0 {
sampleButton.setTitle(String(sampleArray[numberOfItem]), for: .normal)
numberOfItem -= 1
}
else {
sampleTimer.invalidate()
}
}
我是通过设置infoButtonTabbed的内容解决的:
DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.default).async { xxx }
和
中presentArray的内容
DispatchQueue.main.async { xxx }
它现在在数组中循环显示一项接一项。
我正在将信息存储在一个数组中,并希望将其一一呈现在屏幕上的UIButton/UILabel中等待时间为一秒。
当然,系统很聪明,会在更新屏幕之前计算出全部功能以节省资源...我怎样才能防止这种情况并在 运行 每个项目之后更新屏幕? (我使用的是 UIKit 而不是 SpriteKit)。
@objc private func infoButtonTapped(_ sender: Any) {
for item in Array {
statusButton.isHidden = true
updateScreen()
presentArray(item: item)
sleep(1)
}
}
func presentArray(item: ArrayItem) {
statusButton.isHidden = false
statusButton.titleLabel?.text = item.status
}
我试过了
view.setNeedsLayout()
并将特定部分设置为
DispatchQueue.main.async { xxx }
但这些技巧似乎都不起作用...
一个可能的解决方案是使用 scheduledTimer 更新您的按钮或标签,如下所示:
let sampleArray = [0,1,2,3,4,5,6,7,8,9,10]
var numberOfItem = 10
var sampleTimer:Timer!
override func viewDidLoad() {
super.viewDidLoad()
sampleTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(presentArray), userInfo: nil, repeats: true)
}
@objc func presentArray(){
if numberOfItem >= 0 {
sampleButton.setTitle(String(sampleArray[numberOfItem]), for: .normal)
numberOfItem -= 1
}
else {
sampleTimer.invalidate()
}
}
我是通过设置infoButtonTabbed的内容解决的:
DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.default).async { xxx }
和
中presentArray的内容 DispatchQueue.main.async { xxx }
它现在在数组中循环显示一项接一项。