基于时间的问候应用程序无法正常工作

时间:2016-09-18 20:09:48

标签: ios swift xcode

所以我试图在swift中创建一个简单的基于时间的问候语应用程序,但它不起作用,当我在我的应用程序的文本字段中按返回时它只是冻结,Xcode将我带到{{ 1}}并且有一行带有一个小标记,我不知道什么是错的,为什么。

Xcode表示在我编辑代码时代码中没有错误,但是应用程序无法正常工作。这是我的代码:

AppDelegate

感谢任何帮助!

编辑: 我不再需要答案,因为我只是在Swift玩游戏。无论如何,感谢所有回答或评论的人!

-Moose

2 个答案:

答案 0 :(得分:3)

这是我的完整工作应用程序。

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 + "!"

    }

}

答案 1 :(得分:-1)

清洁功能

    private func getGreeting() -> String {
        let hour = Calendar.current.component(.hour, from: Date())

        switch hour {
        case 0..<4:
            return "Hello"
        case 4..<12:
            return "Good morning"
        case 12..<18:
            return "Good afternoon"
        case 18..<24:
            return "Good evening"
        default:
            break
        }
        return "Hello"
    }