我在一个接一个地呈现多个警报控制器时遇到问题。我想要做的是让我的for循环等待,直到用户关闭响应控制器。 我的用于显示消息的代码如下。
for block in blocks {
self.presentMessage(title: codeBlock.stringInput1, message: codeBlock.stringInput2)
}
func presentMessage(title: String, message: String, completion: @escaping (Bool)->()) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Done", style: .default, handler: { action in
completion(true)
}))
self.present(alert, animated: true)
}
编辑-
这是我的积木课
class block: Codable {
var type: String
var stringInput1: String
var stringInput2: String
init(t: String, i1: String, i2: String) {
type = t
stringInput1 = i1
stringInput2 = i2
}
}
我已经尝试使用调度组,但是未能使其正常工作。我的设置的最终目标是使模块能够根据模块的类型执行不同的操作。 如果可能的话,我想让我的for循环等待功能完成,直到继续执行。
答案 0 :(得分:0)
Swift仅允许您一次显示一个视图控制器,因此您必须执行以下操作:
var blocks: [Block] = [Block.init(one: "1", two: "12"),
Block.init(one: "2", two: "22"),
Block.init(one: "3", two: "32")]
func nextMessage(index: Int) {
if index < blocks.count {
let codeBlock = blocks[index]
self.presentMessage(index: index, title: codeBlock.stringInput1, message: codeBlock.stringInput2)
}
}
func presentMessage(index: Int, title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Done", style: .default, handler: { action in
self.nextMessage(index: index + 1)
}))
self.present(alert, animated: true)
}
从数组的第一项中调用presentMessage将启动它:
self.presentMessage(index: 0, title: blocks[0].stringInput1, message: blocks[0].stringInput2)
这是我创建的快速而肮脏的Block类,但是发布了 将来像这样的相关代码将对那些人有帮助 回答问题。
class Block {
var stringInput1: String
var stringInput2: String
init(one: String, two: String) {
stringInput1 = one
stringInput2 = two
}
}
答案 1 :(得分:0)
好的,所以在完成一些工作之后,我将@ elliott-io的答案修改为对我有用的东西。这是我对问题的最终解决方案。
func nextBlock(index: Int) {
if index < codeBlocks.count {
let type = codeBlocks[index].type
if type == "message" {
self.presentMessage(title: codeBlocks[index].stringInput1, message: codeBlocks[index].stringInput2, index: index)
} else if type == "link" {
self.openLink(webpage: codeBlocks[index].stringInput1, index: index)
}
}
}
func presentMessage(title: String, message: String, index: Int) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Done", style: .default, handler: { action in
self.nextBlock(index: index + 1)
}))
self.present(alert, animated: true)
}
之所以使用它作为解决方案,是因为我希望能够拥有一个块可以做的很多事情。