2016-03-14 20 views
6

Potrzebuję, aby tekst pola tekstowego został wybrany zaraz po wyświetleniu elementu UIAlertController. Jednak sposób, w jaki wybieram tekst w standardowym UITextField nie działa tutaj.Zaznaczanie tekstu w polu tekstowym UIAlertController

Oto, co próbowałem, ale nie mogę tego zrobić.

let ac = UIAlertController(title: "Rename", message: nil, preferredStyle: .Alert) 
ac.addTextFieldWithConfigurationHandler({ 
    [] (textField: UITextField) in 
    textField.selectedTextRange = textField.textRangeFromPosition(textField.beginningOfDocument, toPosition: textField.endOfDocument) 
    textField.text = "filename.dat" 
    }) 
ac.addAction(UIAlertAction(title: "CANCEL", style: .Cancel, handler: nil)) 
ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: { 
    [] Void in 
    // do something 
    })) 
dispatch_async(dispatch_get_main_queue(), { 
    self.presentViewController(ac, animated: true, completion: nil) 
}) 

Wszelkie pomysły?

Odpowiedz

9

Przepisałem twój kod. Twoja klasa powinna być zgodna z protokołem UITextFieldDelegate i wdrożenie metody textFieldDidBeginEditing, tak:

class ViewController: UIViewController, UITextFieldDelegate { 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     let ac = UIAlertController(title: "Rename", message: nil, preferredStyle: .Alert) 
     ac.addTextFieldWithConfigurationHandler({ 
      [] (textField: UITextField) in 
      textField.text = "filename.dat" 
      textField.delegate = self 

     }) 
     ac.addAction(UIAlertAction(title: "CANCEL", style: .Cancel, handler: nil)) 
     ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: { 
      [] Void in 
      // do something 
     })) 
     dispatch_async(dispatch_get_main_queue(), { 
      self.presentViewController(ac, animated: true, completion: nil) 
     }) 

    } 
    func textFieldDidBeginEditing(textField: UITextField) { 
     textField.selectedTextRange = textField.textRangeFromPosition(textField.beginningOfDocument, toPosition: textField.endOfDocument) 
     textField.becomeFirstResponder() 
    } 

} 
2

Pozdrawiamy, @ridvankucuk. Twoje rozwiązanie działa świetnie.

Ale funkcja textfield delegat można uprościć trochę:

func textFieldDidBeginEditing(_ textField: UITextField) { 
    textField.selectAll(nil) 
} 
+0

Zauważyłem, że pominięto 'textField.becomeFirstResponder()' z Odpowiedź @ ridvankucuk. Czy są sytuacje, w których linia ta powinna zostać ponownie dodana? – ToolmakerSteve

+1

@ToolmakerSteve, osobiście, nigdy nie spotkałem się z takimi sytuacjami. Pole tekstowe jest już pierwszą odpowiedzią, gdy wywoływana jest metoda 'textFieldDidBeginEditing:'. Ale może być jakiś szczególny przypadek, kiedy musisz zrobić to ponownie jako pierwszy. – seelts

1

Sposób, aby zaznaczyć cały tekst bez dodawania Delegat:

present(vc, animated: true) { 
    vc.textFields![0].selectAll(nil) 
} 
+0

To działało idealnie dla mnie! – lox