gpt4 book ai didi

ios - 如何在 swift 4 中实现 make 处理程序以使代码能够按需要的顺序执行

转载 作者:行者123 更新时间:2023-11-28 13:40:29 25 4
gpt4 key购买 nike

我编写了一个函数,它会弹出一个提示,要求用户进行菜单选择。该选择将用于更改按钮名称。问题是在用户做出选择之前更改了按钮名称。改成了之前的函数结果。

我读到可以使用处理程序来延迟结果的执行,但我不知道如何使用它。

@IBAction func selectProp(_ sender: Any) {
propName.setTitle(menulist(title:"propName", message:""), for: .normal)
print("selected property = ", choice) // }
}

func menulist (title: String, message: String) -> String {
let title1 = "Select Property"
let alert = UIAlertController(title: title1, message: message, preferredStyle:UIAlertControllerStyle.alert)
let k = rentals.count
if k > 0 {
for i in 0 ... k-1 {
alert.addAction(UIAlertAction(title:rentals[i], style: .default, handler: {action in
choice = rentals[i]
print("choice=",choice)
}))
}

alert.addAction(UIAlertAction(title: "Cancel", style: .destructive, handler: {action in
choice = "Select"
print("choice=",choice)
}))

self.present(alert, animated: true, completion: nil)
}
return choice
}

问题是在用户做出选择之前更改了按钮名称,并且在用户做出选择之前执行了打印语句。结果,按钮更改和打印,基于先前的用户输入选择。

最佳答案

I have read that a handler can be used to delay execution of the result, but can't figure out how to use it.

确切地说,这样的处理程序称为闭包。由于 UIAlertAction 使用闭包来传递结果,因此您需要在函数中使用闭包而不是返回值。

func showMenuList(title: String, message: String, completion: @escaping (_ rental: String?) -> ()) {
let title = "Select Property"
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)

// loop through all rentals and add action to alert for each of them
rentals.forEach { (rental) in
let rentalAction = UIAlertAction(title: rental, style: .default, handler: { _ in
completion(rental)
})

alert.addAction(rentalAction)
}

// add cancel action
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: { _ in
completion(nil)
})
alert.addAction(cancelAction)

present(alert, animated: true, completion: nil)
}

然后你可以像这样使用这个函数:

showMenuList(title: "propName", message: "") { result in
guard let result = result else {
// handle Cancel action
return
}

// handle property selected
print(result)
}

关于ios - 如何在 swift 4 中实现 make 处理程序以使代码能够按需要的顺序执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56099522/

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