解雇UIAlertController UITextField上的键盘

时间:2017-10-28 15:52:33

标签: swift uitextfield uialertcontroller

通常view.endEditing(true)总是在iOS上删除swift中的键盘。

然而,并非总是如此,例如UITextFieldself.present()'ed模式view的一部分,即UIAlertController

内的表单

实施例

    let alert = UIAlertController(title: _title, message: "Choose", preferredStyle: .alert)

    let numberLabel = UILabel(frame: CGRect(x:10, y:0, width:90, height:20))
    numberLabel.textColor = .black
    numberLabel.textAlignment = NSTextAlignment.left
    numberLabel.font = UIFont(name: titleLabel.font.fontName, size: 16)
    numberLabel.font = UIFont.boldSystemFont(ofSize: titleLabel.font.pointSize)
    numberLabel.text = "Quantity"

    let quantityField = UITextField(frame: CGRect(x:100, y:0, width:140, height:25))
    quantityField.layer.borderWidth = 1
    quantityField.keyboardType = .numberPad
    quantityField.layer.borderColor = UIColor.lightGray.cgColor
    quantityField.delegate = self
    self.addDoneButtonOnKeyboard(textField: quantityField)
    self.present(alert, animated: true, completion: nil)

现在在这个self.addDoneButtonOnKeyboard方法中我有这个漂亮的代码

func addDoneButtonOnKeyboard(textField: UITextField){
    let doneToolbar: UIToolbar = UIToolbar(frame: CGRect(x:0, y:0, width:320, height:50))
    doneToolbar.barStyle = UIBarStyle.default

    let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
    let done: UIBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.done, target: self, action: #selector(ViewControllerDisplay.doneButtonAction(_:)))

    let items = NSMutableArray()
    items.add(flexSpace)
    items.add(done)

    doneToolbar.items = items as? [UIBarButtonItem]
    doneToolbar.sizeToFit()

    textField.inputAccessoryView = doneToolbar
}

@objc func doneButtonAction(_ btn: UIBarButtonItem){
    view.endEditing(true)
}

所有这一切的目的是出现“完成”键盘按钮。确实如此。事实上它看起来很棒,我也可以捕获doneButtonAction()这个很棒的事件,但我只捕获UIBarButtonItem所以我不能使用UITextField.resignFirstResponder()方法,即使我知道它将工作。我必须使用“查看”

我想要做的是致电alert.endEditting(true),但我已尝试在子视图中循环,筛选UIAlertController的任何事件,但self.present不能正常工作

任何人都可以帮我清除警报视图中的键盘吗?

1 个答案:

答案 0 :(得分:0)

我通过获取topMost视图控制器来修复它,然后调用endEditing(true)我认为这个问题应该继续保持,这对某人来说是非常有用的一点点

@objc func doneButtonAction(_ btn: UIBarButtonItem){
    if var topController = UIApplication.shared.keyWindow?.rootViewController {
        while let presentedViewController = topController.presentedViewController {
            topController = presentedViewController
        }
        topController.view.endEditing(true)
    }
}