Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Tee Abdul
8,411 PointsThe UITextField kind of disappears instead of moving up
I can still type and start the adventure, but I can't see what I'm typing. Any idea where I could've messed up?
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
enum Error: ErrorType {
case NoName
}
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var textFieldBottomConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "startAdventure" {
do {
if let name = nameTextField.text {
if name == "" {
throw Error.NoName
}else {
if let pageController = segue.destinationViewController as? PageController {
pageController.page = Adventure.story(name)
}
}
}
} catch Error.NoName{
let alertController = UIAlertController(title: "Name not provided", message: "Provide a name to start your story", preferredStyle: .Alert)
let action = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertController.addAction(action)
presentViewController(alertController, animated: true, completion: nil)
} catch let error {
fatalError("\(error)")
}
}
}
func keyboardWillShow(notification: NSNotification) {
if let userInfoDict = notification.userInfo,
keyboardFrameValue = userInfoDict[UIKeyboardFrameEndUserInfoKey] as? NSValue {
let keyboardFrame = keyboardFrameValue.CGRectValue()
UIView.animateWithDuration(0.8) {
self.textFieldBottomConstraint.constant = keyboardFrame.size.height + 10
self.view.layoutIfNeeded()
}
}
}
// MARK: - UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}