我想使用swift在xcode中使用datePicker将一周中的某一天存储为字符串。
答案 0 :(得分: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)
}
}
答案 1 :(得分:-1)
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.
}
}