I want to store just the day of the week as a string using a datePicker in xcode using swift.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var myDatePicker: UIDatePicker!
@IBOutlet weak var strWeekday: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// set mode to date only
myDatePicker.datePickerMode = UIDatePickerMode.Date
// add target for the trigger update function to change the weekday when the user changes the date
myDatePicker.addTarget(self, action: Selector("triggerUpdate:"), forControlEvents: UIControlEvents.ValueChanged)
// weekday initial value
self.strWeekday.text = myDatePicker.date.weekdayName
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func triggerUpdate(sender: AnyObject) {
self.strWeekday.text = myDatePicker.date.weekdayName
}
}
extension NSDate {
// returns weekday name (Sunday-Saturday) as String
var weekdayName: String {
let formatter = NSDateFormatter(); formatter.dateFormat = "EEEE"
return formatter.stringFromDate(self)
}
}
回答2:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var datePicker: UIDatePicker!
@IBAction func displayDay(sender: AnyObject) {
// grab the selected date from the date picker
var chosenDate = self.datePicker.date
// create an NSDateFormatter
var formatter = NSDateFormatter()
formatter.dateFormat = "EEEE"
// grab the day and create a message
let day = formatter.stringFromDate(chosenDate)
let result = "That was a \(day)"
// create alert controller
let myAlert = UIAlertController(title: result, message: nil, preferredStyle: UIAlertControllerStyle.Alert)
// add an "OK" button
myAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
// show the alert
self.presentViewController(myAlert, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}