2017-01-14 22 views
0

我的想法是在工作中製作一個顯示今天午餐的ios應用程序。我不知道如何解決這個問題。我自己的想法是有一個UIDatePicker(默認設置爲當天)並具有將響應不同日期的函數。這是一些代碼,只是爲了說明我腦海中的想法。如何讓標籤在指定的日期使用不同的字符串?

var dateFromPicker = UIDatePicker.date 
@IBOutlet weak var lunchLabel: UILabel! 

func februaryFirst { 
    let dateFebruaryFirst = ... 
    if dateFromPicker = dateFebruaryFirst { 
     lunchLabel.text = ("Fish'n chips") 
    } 
} 

func februarySecond { 
    let dateFebruarySecond = ... 
    if dateFromPicker = dateFebruarySecond { 
     lunchLabel.text = ("Noodlesoup") 
    } 
} 

回答

0

您可能想使用DateComponents來檢查某個日期是哪天/每月。例如:

func februarySecond { 
    // Get the day and month of the given date 
    let dateFromPickerComponents = Calendar.current.dateComponents([.day, .month], from: dateFromPicker) 
    // Check whether the day and month match Feb 2 
    if dateFromPickerComponents.day == 2 && dateFromPickerComponents.month == 2 { 
     lunchLabel.text = ("Noodlesoup") 
    } 
} 
0

你可以使用一個switch聲明,支持多個值:

let dateFromPicker = UIDatePicker.date 
let components = Calendar.current.dateComponents([.month, .day], from: dateFromPicker) 
switch (components.month!, components.day!) { // first month then day 
    case (1,14): print("suprise") 
    case (2,1): print("Fish'n chips") 
    case (2,2): print("Noodlesoup") 

    default: print("fast day") 

} 
相關問題