Displaying the Day Of The Week From Date Picker

2019-01-12 08:06发布

I want to store just the day of the week as a string using a datePicker in xcode using swift.

2条回答
走好不送
2楼-- · 2019-01-12 08:48
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)
    }
}
查看更多
狗以群分
3楼-- · 2019-01-12 08:59
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.
    }


}
查看更多
登录 后发表回答