UITextFields

Aus Wikizone
Wechseln zu: Navigation, Suche
UIKit Framework

UITextFields nutzt man für Benutzereingaben. Der Benutzer kann über das Handykeyboard Eingaben machen. Es gibt viele Konfigurationsmöglichkeiten z.B.:

  • Art des Keyboards
  • Automatische Traits (z.B. jedes Wort mit Großbuchstaben beginnen etc.)
  • Im Property Inspektor im View finden sich die meisten Eigenschaften

Beispiele[Bearbeiten]

Beispiel mit Delegate[Bearbeiten]

import UIKit

class WeatherViewController: UIViewController, UITextFieldDelegate { // get the delegate methods

    @IBOutlet weak var conditionImageView: UIImageView!
    @IBOutlet weak var temperatureLabel: UILabel!
    @IBOutlet weak var cityLabel: UILabel!
    
    @IBOutlet weak var searchTextField: UITextField!
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Delegate the searchTextField to the view
        searchTextField.delegate = self
    }

    @IBAction func searchPressed(_ sender: UIButton) {
        print(searchTextField.text!)
        searchTextField.endEditing(true)
    }
    
    /**
     Note: We can now use the functions below because we delegated the searchTextField to the view (see avove)
     Now the textField reports to the view about what's happening and we can decide what to do
     The textField triggers these methods and passes a reference to itself so we can react to it.
     
     This way we can also use the same textField functions for multiple textFields
     */
    
    // Close the keyboard when editing ends
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        print(textField.text!)
        textField.endEditing(true)
        return true
    }
    
    /**
     Note: The "Should" functions allow to decide the controller what to do.I.e. hiere we can
     prevent end edtiting if user didn't type anything
     */
    func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
        if searchTextField.text != "" {
            return true  
        }
        else {
            textField.placeholder = "Type anything"
            return false
        }
    }
    
    // Empty the input after editing
    func textFieldDidEndEditing(_ textField: UITextField) {
        let place = searchTextField.text
        // or let place = textField.text if it's the only one
        
        // reset the value
        textField.text = ""
    }
}