0

i'm trying to create a function using a uialertcontroller with textfield using extension uialertcontroller

this is my code :

extension UIAlertController{ class func AlertWithTextField(here: String, message1 : String) -> UIAlertController{ var alertController:UIAlertController? alertController = UIAlertController(title: here, message: message1, preferredStyle: .Alert) alertController!.addTextFieldWithConfigurationHandler( {(textField: UITextField!) in textField.placeholder = "Ex: 1" textField.textAlignment = .Center textField.delegate = self textField.keyboardType = UIKeyboardType.NumberPad }) let action = UIAlertAction(title: "Submit", style: UIAlertActionStyle.Default, handler: {[weak self] (paramAction:UIAlertAction!) in if let textFields = alertController?.textFields{ let theTextFields = textFields as! [UITextField] let enteredText = theTextFields[0].text print("\n\(enteredText)") } }) let action2 = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil) alertController?.addAction(action) alertController?.addAction(action2) }} 

okay, i have problem with the words "self", and i can't found solution for them, what could be the solution for this problem ??

1

1 Answer 1

0

For your first self problem, i would suggest you do something like this

 class func AlertWithTextField(here: String, message1 : String, delegate:UITextFieldDelegate?) -> UIAlertController{ var alertController:UIAlertController? alertController = UIAlertController(title: here, message: message1, preferredStyle: .Alert) alertController!.addTextFieldWithConfigurationHandler( {(textField: UITextField!) in textField.placeholder = "Ex: 1" textField.textAlignment = .Center textField.delegate = delegate textField.keyboardType = UIKeyboardType.NumberPad }) let action = UIAlertAction(title: "Submit", style: UIAlertActionStyle.Default, handler: {(paramAction:UIAlertAction!)->Void in if let textFields = alertController?.textFields { let theTextFields = textFields let enteredText = theTextFields[0].text print("\n\(enteredText)") } }) let action2 = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil) alertController?.addAction(action) alertController?.addAction(action2) return alertController! } 

You can accept a UITextFieldDelegate object in your static methods and assign it ti the delegate and for your second problem you are declaring weak self but not using it in the closure so just remove that and your code should work fine.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.