Help us understand the problem. What is going on with this article?

NSCalendarクラス

More than 3 years have passed since last update.

swift2, Xcode7.2.1

Class Reference : NSCalendar

ObjectEx.swift
import UIKit

//オブジェクト
//UIViewクラスを継承
//プロジェクト名と同じクラス名
class ObjectEx: UIView {

    //描画時に呼ばれる
    override func drawRect(rect: CGRect) {
        //オブジェクト型の変数の定義
        //イニシャライザはすべての引数でラベル必要(1)
        let calendar: NSCalendar =
            NSCalendar(calendarIdentifier:
            NSCalendarIdentifierGregorian)! //和暦の場合はNSCalendarIdentifierJapanese
            // ! オプショナルな変数->通常変数(2)

        //取得情報フラグの準備(3)
        //構造体.プロパティ名(4)(5)
        let flags: NSCalendarUnit = [
            NSCalendarUnit.Year,   //年
            NSCalendarUnit.Month,  //月
            NSCalendarUnit.Day,    //日
            NSCalendarUnit.Hour,   //時
            NSCalendarUnit.Minute] //分

        //日付コンポーネントの取得
        //オブジェクト名.メソッド名(引数1, ラベル:引数2)
        //メソッドは第二引数以降でラベル指定
        //ここではflagと現在時刻を渡す
        let comps = calendar.components(flags, fromDate: NSDate())

        //年月日の取得
        let year = comps.year     //年
        let month = comps.month   //月
        let day = comps.day       //日
        let hour = comps.hour     //時
        let minute = comps.minute //分

        //文字列の描画
        let str = "\(year)\(month)\(day)\(hour)\(minute)分"
        drawString(str, x: 0, y: 20)
    }

    //文字列の描画
    func drawString(str: String, x: Int, y: Int) {
        let attrs = [NSFontAttributeName: UIFont.systemFontOfSize(24)]
        str.drawAtPoint(CGPointMake(CGFloat(x), CGFloat(y)),
            withAttributes: attrs)
    }
}

注釈

1.イニシャライザ
構造体とクラスで初期化のために使用

2.オプショナル変数
オプショナル変数を利用するにはアンラップする必要がある

3.NSCalendarUnit
NSCalendarUnitはなにをしているのか

4.構造体とは
クラスは参照渡し、構造体は値渡し
Swiftのクラスと構造体の使い分けについてのメモ

5.flagの書き方は省略できる
Swift カレンダー,日付系備忘録

6.フォーマットを使う
-> NSDateFormatter
知っておくと便利なローカライズ関連Tips
NSDateFormatterの使い方まとめ


参考
iPhone/iPadプログラミングバイブル iOS9/Xcode7/Swift 対応

mo49
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした