小编典典

从日期选择器显示星期几

swift

我想使用swift在xcode中使用datePicker将星期几仅存储为字符串。


阅读 437

收藏
2020-07-07

共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)
    }
}
2020-07-07