[ios] Swift에서 UIAlertController에 TextField를 추가하는 방법

나는 보여주기 위해 노력하고 UIAlertControllerA를을 UITextView. 줄을 추가 할 때 :

    //Add text field
    alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in
    }

내가 얻을 Runtime오류 :

치명적 오류 : 선택적 값을 언 래핑하는 동안 예기치 않게 nil이 발견되었습니다.

    let alertController: UIAlertController = UIAlertController(title: "Find image", message: "Search for image", preferredStyle: .Alert)

    //cancel button
    let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in
        //cancel code
    }
    alertController.addAction(cancelAction)

    //Create an optional action
    let nextAction: UIAlertAction = UIAlertAction(title: "Search", style: .Default) { action -> Void in
        let text = (alertController.textFields?.first as! UITextField).text
        println("You entered \(text)")
    }
    alertController.addAction(nextAction)

    //Add text field
    alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in
        textField.textColor = UIColor.greenColor()
    }
    //Present the AlertController
    presentViewController(alertController, animated: true, completion: nil)

이것은 나의 내부에 제시 ViewController를 통해 IBAction.

여기 에서 코드를 다운로드했으며 정상적으로 작동합니다. 이 메서드를 복사하여 내 코드에 붙여 넣었 더니 깨졌습니다. 의 존재 자체 마지막 줄에 아무 영향을주지 않습니다.



답변

스위프트 5.1

alert.addTextField { (textField) in
    textField.placeholder = "Enter First Name"
}

이 코드를 사용하면 내 앱에서이 코드를 성공적으로 실행하고 있습니다.

@IBAction func addButtonClicked(sender : AnyObject){
    let alertController = UIAlertController(title: "Add New Name", message: "", preferredStyle: UIAlertControllerStyle.Alert)
    alertController.addTextFieldWithConfigurationHandler { (textField : UITextField!) -> Void in
        textField.placeholder = "Enter Second Name"
    }
    let saveAction = UIAlertAction(title: "Save", style: UIAlertActionStyle.Default, handler: { alert -> Void in
        let firstTextField = alertController.textFields![0] as UITextField
        let secondTextField = alertController.textFields![1] as UITextField
    })
    let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: {
        (action : UIAlertAction!) -> Void in })
    alertController.addTextFieldWithConfigurationHandler { (textField : UITextField!) -> Void in
        textField.placeholder = "Enter First Name"
    }

    alertController.addAction(saveAction)
    alertController.addAction(cancelAction)

    self.presentViewController(alertController, animated: true, completion: nil)
}

편집 됨 : Swift 3.0 버전

@IBAction func addButtonClicked(_ sender: UIButton){
    let alertController = UIAlertController(title: "Add New Name", message: "", preferredStyle: .alert)
    alertController.addTextField { (textField : UITextField!) -> Void in
        textField.placeholder = "Enter Second Name"
    }
    let saveAction = UIAlertAction(title: "Save", style: .default, handler: { alert -> Void in
        let firstTextField = alertController.textFields![0] as UITextField
        let secondTextField = alertController.textFields![1] as UITextField
        print("firstName \(firstTextField.text), secondName \(secondTextField.text)")
    })
    let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: { (action : UIAlertAction!) -> Void in })
    alertController.addTextField { (textField : UITextField!) -> Void in
        textField.placeholder = "Enter First Name"
    }

    alertController.addAction(saveAction)
    alertController.addAction(cancelAction)

    self.present(alertController, animated: true, completion: nil)
}


답변

Swift 3.0에서 텍스트 필드를 추가하려면 :

let alertController = UIAlertController(title: "Title", message: "", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Save", style: .default, handler: { alert -> Void in
    let textField = alertController.textFields![0] as UITextField
    // do something with textField
}))
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
alertController.addTextField(configurationHandler: {(textField : UITextField!) -> Void in
    textField.placeholder = "Search"
})
self.present(alertController, animated: true, completion: nil)


답변

그래서 나는 내 코드에서 작업 코드와 무엇이 다를 수 있는지 확인하기 시작했습니다. 내 ViewController가 확장된다는 것을 알았습니다.

UITextFieldDelegate

이는 자식 UITextView의 대리자를 설정해야 함을 의미합니다.

alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in
    searchTextField = textField
    searchTextField?.delegate = self //REQUIRED
    searchTextField?.placeholder = "Enter your search terms"
}


답변

해결책:

스위프트 4.2

다음 줄을 시도하고 작동하는지 확인하십시오.

let alertController = UIAlertController(title: "Add New Name", message: "", preferredStyle: .alert)

alertController.addTextField { (textField : UITextField!) -> Void in
    textField.placeholder = "Enter Second Name"
}

let saveAction = UIAlertAction(title: "Save", style: .default, handler: { alert -> Void in
    let firstTextField = alertController.textFields![0] as UITextField
    let secondTextField = alertController.textFields![1] as UITextField
})

let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil )

alertController.addTextField { (textField : UITextField!) -> Void in
    textField.placeholder = "Enter First Name"
}

alertController.addAction(saveAction)
alertController.addAction(cancelAction)

self.present(alertController, animated: true, completion: nil)

도움이 되었기를 바랍니다.


답변

AlertView에 textField를 추가하는 방법은 무엇입니까? 짧고 간단하게합시다.

이것은 Swift 3.0 이상에서 작동합니다.

var nameField: UITextField?
let alertController = UIAlertController(title: "Add Number", message: nil, preferredStyle: .alert)
// Add textfield to alert view
alertController.addTextField { (textField) in
    nameField = textField
}

먼저의 개체를 인스턴스화 한 UIAlertController다음 클래스 addTextField구성원 에 액세스하여 텍스트 필드를 추가합니다 UIAlertController.


답변

하나의 textField가있는 alertController를 추가하려면 (Swift 5)

func openAlert(){
    let alertController = UIAlertController(title: "Title", message: "", preferredStyle: .alert)
    alertController.addTextField { (textField : UITextField!) -> Void in
        textField.placeholder = "Enter name"
    }

    let saveAction = UIAlertAction(title: kAlertConfirm, style: .default, handler: { alert -> Void in
        if let textField = alertController.textFields?[0] {
            if textField.text!.count > 0 {
                print("Text :: \(textField.text ?? "")")
            }
        }
    })

    let cancelAction = UIAlertAction(title: kAlertCancel, style: .default, handler: {
        (action : UIAlertAction!) -> Void in })

    alertController.addAction(cancelAction)
    alertController.addAction(saveAction)

    alertController.preferredAction = saveAction

    self.present(alertController, animated: true, completion: nil)
}


답변

Swift 4.0의 경우 프로젝트에서 성공적으로 테스트 된이 코드 샘플을 사용할 수 있습니다.

@IBAction func withdrawTapped(_ sender: UIButton) {

  let alertController = UIAlertController(title: "Token withdraw", message: "", preferredStyle: .alert)

  let withdrawAction = UIAlertAction(title: "Withdraw", style: .default) { (aciton) in

    let text = alertController.textFields!.first!.text!

    if !text.isEmpty {
      self.presentAlert(
        title: "Succesful",
        message: "You made request for withdraw \(textField.text) tokens")
    }
  }

  let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (action) in
  }

  alertController.addTextField { (textField) in
    textField.placeholder = "999"
    textField.keyboardType = .decimalPad
  }

  alertController.addAction(withdrawAction)
  alertController.addAction(cancelAction)

  self.present(alertController, animated: true, completion: nil)
}