Moosecoop Moosecoop - 1 year ago 180
Swift Question

Time based greeting app not working, swift

So I'm trying to make a simple time based greeting app in swift but it's not working, when I press return in the text field of my app it just freezes, Xcode brings me to

AppDelegate
and has one line with a little mark on it, I don't know whats wrong and why.

Xcode says there are no errors in my code while I'm editing it, but then the app doesn't work. Here's my code:

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var nameLabel: UILabel!

override func viewDidLoad() {
super.viewDidLoad()
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}

@IBAction func nameTextField(nameTextField: UITextField) {
var currentTimeOfDay = ""

let hour = NSCalendar.current.component(.hour, from: NSDate() as Date)
if hour >= 0 && hour < 12 {

currentTimeOfDay = "Morning"

} else if hour >= 12 && hour < 17 {

currentTimeOfDay = "Afternoon"

} else if hour >= 17 {

currentTimeOfDay = "Evening"

}

nameLabel.text = "Good \(currentTimeOfDay) \(nameTextField)"
}
}


Any help is appreciated!

EDIT:
I am no longer in need of the answer as I was just playing around in Swift. Thank you anyway to all who answered or commented though!

-Moose

Answer Source

Here's my full working app.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var helloLbl: UILabel!
    @IBOutlet weak var nameText: UITextField!

    var heyName = "Hey"
    var greeting = ""


    func greetingLogic() {
    let date = NSDate()
    let calendar = NSCalendar.current
    let currentHour = calendar.component(.hour, from: date as Date)
    let hourInt = Int(currentHour.description)!

    if hourInt >= 12 && hourInt <= 16 {
    greeting = "Good Afternoon"
    }
    else if hourInt >= 7 && hourInt <= 12 {
    greeting = "Good Morning"
    }
    else if hourInt >= 16 && hourInt <= 20 {
    greeting = "Good Evening"
    }
    else if hourInt >= 20 && hourInt <= 24 {
    greeting = "Good Night"
    }
    else if hourInt >= 0 && hourInt <= 7 {
    greeting = "You should be sleeping right now"
    }

    helloLbl.text = greeting
        }

    override func viewDidLoad() {
        super.viewDidLoad()

        greetingLogic()

    }


    @IBAction func sayHello(_ sender: UIButton) {

        helloLbl.text = greeting + ", " + nameText.text!.capitalized + "!"

    }

}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download