【发布时间】:2020-08-07 03:12:48
【问题描述】:
我对 iOS 非常陌生。我正在尝试向用户显示一个对话框以获取一些输入,但这些操作从未被触发。我已经在网上搜索了几个小时,但似乎没有任何答案适合我。
这是我试图用来显示对话框的函数:
private func showAmountDialog(type: String, onComplete: @escaping (Double) -> Void) {
let alert = UIAlertController(title: "Enter an amount", message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: LzStrings.Common_Cancel, style: .cancel, handler: nil))
alert.addTextField(configurationHandler: { textField in
textField.placeholder = "0.00 \(type)"
textField.keyboardType = .decimalPad
})
alert.addAction(UIAlertAction(title: LzStrings.Common_OK, style: .default) { (UIAlertAction) in
if let input = alert.textFields?.first?.text, let amount = Double(input) {
print("Your amount: \(amount)")
}
})
self.present(alert, animated: true)
}
self 这是我的ViewController,它有一个UIViewController 类型的父级和其他几个协议。
我可能做错了什么?
编辑:我知道它不执行的方式是使用断点,而不是依赖print("...")
另外,由于我在添加动作之前添加了TextField,所以可空性检查是无用的,textFields.first 永远不会是nil,所以在这两种情况下,都应该触发断点或@987654329 @ 应该被执行,它们都没有发生。
编辑 2:由于 if statement 会分散注意力,我以这种方式编辑了我的代码并再次测试:
alert.addAction(UIAlertAction(title: LzStrings.Common_OK, style: .default) { (UIAlertAction) in
if let input = alert.textFields?.first {
if let amount = Double(input.text ?? "") {
print("Your amount: \(amount)")
} else {
print("Can't cast this string to double")
}
} else {
print("Text field is null")
}
})
仍然没有来自dialog 的反馈。
PS:即使是 Cancel button 也不起作用。
编辑 3:我的解雇 function 在 super 类中被覆盖,但它通常通过完成 closure:
override open func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) {
if let navigationController = self.navigationController as? NavigationController {
navigationController.dismiss(animated: flag, completion: completion)
} else {
super.dismiss(animated: flag, completion: completion)
}
}
【问题讨论】:
-
它不工作是因为
print("Your amount: \(amount)")打印不正确?那么,是因为alert.textFields?.first?.text为零,还是因为Double(input)为零? -
正如@Larme 所说,您为什么认为它有效?
-
@Larme,我没有依赖 print() 的输出,我在可空性检查行上放了一个断点
-
我编辑了问题
-
let amount = Double(input)是零吗?这就是失败的原因吗?你能把你的if let ... {}换成if let ... {} else { print("oops") }吗?
标签: ios swift iphone uiviewcontroller dialog