Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Build an Interactive Story App with Swift Adding Sound Effects Repositioning the Text Field

Sayuri Katz
Sayuri Katz
6,148 Points

the keyboard doesn't show up.

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var textFieldBottomConstraint: NSLayoutConstraint!

override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow(_:)), name: Notification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide(_:)), name: .UIKeyboardWillHide, object: nil)

    func keyboardWillHide(_ notification: Notification) {
        textFieldBottomConstraint.constant = 40

        UIView.animate(withDuration: 0.8) {
            self.view.layoutIfNeeded()
        }
    }

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "startAdventure" {

        do {
            if let name = nameTextField.text {
                if name == "" {
                    throw AdventureError.nameNotProvided
                } else {
                    guard let pageController = segue.destination as? PageController else { return }

                    pageController.page = Adventure.story(withName: name)
                }
            }
        } catch AdventureError.nameNotProvided {
            let alertController = UIAlertController(title: "Name Not Provided", message: "Provide a name to start the story", preferredStyle: .alert)

            let action = UIAlertAction(title: "OK", style: .default, handler: nil)
            alertController.addAction(action)

            present(alertController, animated: true, completion: nil)
        } catch let error {
            fatalError("\(error.localizedDescription)")
        }
    }
}

func keyboardWillShow(_ notification: Notification) {
    if let info = notification.userInfo, let keyboardFrame = info [UIKeyboardFrameEndUserInfoKey] as? NSValue {
        let frame = keyboardFrame.cgRectValue
        textFieldBottomConstraint.constant = frame.size.height + 10

        UIView.animate(withDuration: 0.8) {
            self.view.layoutIfNeeded()
        }
    }
}

func keyboardWillHide(_ notification: Notification) {
    textFieldBottomConstraint.constant = 40

    UIView.animate(withDuration: 0.8) {
        self.view.layoutIfNeeded()
    }
}

deinit {
    NotificationCenter.default.removeObserver(self)
}

}

extension ViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }

1 Answer

Hi! What is working for me is to go to override func viewDidLoad() { } and inside it write, yourTextField.becomeFirstResponder()