2016-04-21 3 views
5

У меня есть UIAlertController (Alert style) в Swift, и все работает отлично. Тем не менее, UITextField, который я добавил к нему, является необязательным полем, в котором пользователю не требуется вводить текст. Проблема в том, что когда я показываю это UIAlertController, клавиатура появляется одновременно с выбранным по умолчанию текстовым полем. Я не хочу, чтобы клавиатура появлялась, если пользователь не нажал UITextField. Как это может быть сделано?Предотвращение автоматического появления клавиатуры с помощью UIAlertController

let popup = UIAlertController(title: "My title", 
     message: "My message", 
     preferredStyle: .Alert) 
    popup.addTextFieldWithConfigurationHandler { (optionalTextField) -> Void in 
     optionalTextField.placeholder = "This is optional" 
    } 
    let submitAction = UIAlertAction(title: "Submit", style: .Cancel) { (action) -> Void in 
     let optionalTextField = popup.textFields![0] 
     let text = optionalTextField.text 
     print(text) 
    } 
    let cancelAction = UIAlertAction(title: "Cancel", style: .Default, handler: nil) 
    popup.addAction(cancelAction) 
    popup.addAction(submitAction) 
    self.presentViewController(popup, animated: true, completion: nil) 
+2

вы должны сделать becomeFirstResponder позвонить куда-нибудь еще. Или вы можете позвонить self.view endEditing: YES после/перед представлением предупреждения. –

ответ

4

это должно сделать трюк:

сделать ваш ViewController соответствовать UITextFieldDelegate

назначить popup.textFields![0].delegate для self

добавить уникальный тег в popup.textFields![0] (я использовал 999 в примере ниже)

осуществить это

func textFieldShouldBeginEditing(textField: UITextField) -> Bool { 
    if textField.tag == 999 { 
    textField.tag = 0 
    return false 
    }else{ 
    return true 
    } 
} 

ваш код должен выглядеть следующим образом:

let popup = UIAlertController(title: "My title", 
            message: "My message", 
            preferredStyle: .Alert) 
    popup.addTextFieldWithConfigurationHandler { (optionalTextField) -> Void in 
     optionalTextField.placeholder = "This is optional" 
    } 
    popup.textFields![0].delegate = self 
    popup.textFields![0].tag = 999 
    let submitAction = UIAlertAction(title: "Submit", style: .Cancel) { (action) -> Void in 
     let optionalTextField = popup.textFields![0] 
     let text = optionalTextField.text 
     print(text) 
    } 
    let cancelAction = UIAlertAction(title: "Cancel", style: .Default, handler: nil) 
    popup.addAction(cancelAction) 
    popup.addAction(submitAction) 
    self.presentViewController(popup, animated: true, completion: nil) 
+1

ха-ха большие мысли думают одинаково eh: P –

3

Я думаю, что это поведение по умолчанию для TextField в тревоге, может рассмотреть альтернативный проект так, чтобы текстовое поле только появляется, когда это необходимо ...

Теперь с этим не будем обходить это!

Когда вы добавляете textField, сделайте свой viewController его делегатом и добавьте к нему тег.

например

popup.addTextFieldWithConfigurationHandler { (optionalTextField) -> Void in 
    optionalTextField.placeholder = "This is optional" 
    optionalTextField.delegate = self 
    optionalTextField.tag = -1 
} 

затем реализовать textFieldShouldBeginEditing()

func textFieldShouldBeginEditing(textField: UITextField!) { 
    if textField.tag == -1 { 
     textField.tag = 0 
     return false 
    } else { 
     return true 
    } 
} 
Смежные вопросы