LoginSignup
3
2

More than 5 years have passed since last update.

【swift 4】△年○月1日は何曜日か?がわかるアプリ

Last updated at Posted at 2018-03-17

iOSでカレンダーアプリを作る場合、「△年○月1日は何曜日か?」を始めに求めなければいけません。カレンダーのレイアウトに関しては、いろんなサンプルが出ていますので、各月の1日が何曜日かがわかるシンプルなアプリを作ってみました。

weekdayOfFirstDay.gif

LabelをdateLabel
「<前月」をzengetsuButton、
「次月>」をjigetsuButtonとしました。


import UIKit

class ViewController: UIViewController {

    @IBOutlet var dateLabel:UILabel!
    @IBOutlet var zengetsuButton:UIButton!
    @IBOutlet var jigetsuButton:UIButton!

    let now = Date()
    var cal = Calendar.current
    let dateFormatter = DateFormatter()
    var components = DateComponents()

    override func viewDidLoad() {
        super.viewDidLoad()
        cal.locale = Locale(identifier: "ja")
        dateFormatter.locale = Locale(identifier: "ja_JP")
        dateFormatter.dateFormat = "yyyy年M月d日EEEE"
        components.year = cal.component(.year, from: now)
        components.month = cal.component(.month, from: now)
        components.day = 1
        calculation()
    }

    func calculation(){
        let firstDayOfMonth = cal.date(from: components)
        dateLabel.text = dateFormatter.string(from: firstDayOfMonth!)
    }

//<前月 を押した時のAction
    @IBAction func myActionZengetsu(){
        components.month = components.month! - 1
        calculation()
    }

//次月> を押した時のAction
    @IBAction func myActionJigetsu(){
        components.month = components.month! + 1
        calculation()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

実際に起動させると、年をまたいでも正確に1日の曜日が求められることが分かります。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2