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

标签 ios swift uialertcontroller

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

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

@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/

相关文章:

ios - 传递给 UIModule 的方法 (createTableViewRow) 无效

ios - 在自定义 TableViewCell 中按下按钮时从 API 打开 URL

ios - 如何更改 UIAlertController 的角半径

ios - UIAlertAction 按钮文本左对齐

Swift - 存储 UIAlertController 文本值

ios - JavaFXPorts 和 robovm-cocoatouch 导入

objective-c - UIPageControl - 尽管 hidesForSinglePage 为真,但孤独指示器可见

ios - 如何检查当前用户之前是否登录过

ios - 应用程序到达前台后呈现模式的最佳方法

swift - 在 watchOS 3 中提取纹理