UITextFields

Aus Wikizone
Version vom 7. Januar 2023, 08:21 Uhr von 134.3.86.14 (Diskussion) (Die Seite wurde neu angelegt: „UITextFields nutzt man für Benutzereingaben. Der Benutzer kann über das Handykeyboard Eingaben machen. Es gibt viele Konfigurationsmöglichkeiten z.B.: * Ar…“)
(Unterschied) ← Nächstältere Version | Aktuelle Version (Unterschied) | Nächstjüngere Version → (Unterschied)
Wechseln zu: Navigation, Suche

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

Beispiel mit Delegate

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 // enables the textfield to report to the WeatherViewController
    }

    @IBAction func searchPressed(_ sender: UIButton) {
        print(searchTextField.text!)
        searchTextField.endEditing(true)
    }
    
    /**
     Note: We can use this textField functins now because we delegated the searchTextField to the view (see avove)
     Now the textField can report to the view and we can decide via controller what to do
     The textField does this by triggering the  methods below and passing a reference to itself so we can react to it.
     
     This way we can use 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 = ""
    }
}