xcode 从日期选择器显示星期几
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27326196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 06:19:41 来源:igfitidea点击:
Displaying the Day Of The Week From Date Picker
提问by Nolan Betts
I want to store just the day of the week as a string using a datePicker in xcode using swift.
我想使用 swift 在 xcode 中使用 datePicker 将星期几存储为字符串。
回答by Leo Dabus
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)
}
}
回答by Durul Dalkanat
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.
}
}