【Swift・iOS】Realm✖️FSCalendar シンプルなカレンダー

Swift

モバイルアプリのDBで有名なRealmとFSCalendarを使ってシンプルなカレンダーを作成しています。自分の備忘録としてここに記載いたします。

カレンダー画面

import UIKit
import FSCalendar
import RealmSwift

class ViewController: UIViewController {

    fileprivate weak var calendar: FSCalendar!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // In loadView or viewDidLoad
        let calendar = FSCalendar(frame: CGRect(x: 0, y: 0, width: 320, height: 300))
        calendar.dataSource = self
        calendar.delegate = self
        calendar.register(FSCalendarCell.self, forCellReuseIdentifier: "CELL")
        //Auto Layout以前に使われていた制約を解除しないといけない
        calendar.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(calendar)
        
        //レイアウト制約
        calendar.centerYAnchor.constraint(equalTo: view.topAnchor, constant: 250).isActive = true
        calendar.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        calendar.heightAnchor.constraint(equalToConstant: 275).isActive = true
        calendar.widthAnchor.constraint(equalToConstant: view.frame.width - 40).isActive = true
        
        self.calendar = calendar
        view.backgroundColor = .white
        Button()
        Label()
    }
    
    //MARK: -Function
    
    func Button() {
        let button = UIButton(frame: CGRect(x: 300, y: 700, width: 100, height: 100))
        button.backgroundColor = .orange
        button.addTarget(self, action: #selector(tapButton), for: .touchUpInside)
        button.layer.cornerRadius = button.bounds.width / 2
        button.layer.masksToBounds = true
        view.addSubview(button)
    }
    
    func Label() {
        let label = UILabel(frame: CGRect(x: 0, y: 500, width: 400, height: 50))
        label.text = "a"
        label.textAlignment = .center
        label.font = UIFont.systemFont(ofSize: 20.0)
        view.addSubview(label)
    }
    
    
    //ボタンを押したときの処理
    @objc func tapButton() {
        let addEventVC = AddEventViewController()
        present(addEventVC, animated: true, completion: nil)
    }
}


//MARK: -CalendarSupport
extension ViewController: FSCalendarDelegate, FSCalendarDataSource {

    
    func calendar(_ calendar: FSCalendar, cellFor date: Date, at position: FSCalendarMonthPosition) -> FSCalendarCell {
        let cell = calendar.dequeueReusableCell(withIdentifier: "CELL", for: date, at: position)
        return cell
    }
    
   
    
}

イベント追加画面


import UIKit
import RealmSwift

class AddEventViewController: UIViewController {

    let datePickerText = UILabel()
    let textView  = UITextView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        TextView()
        Button()
        DatePicker()
        view.backgroundColor = .white
    }
    
    
    //MARK: -ViewFunction
    func TextView() {
        textView.frame = CGRect(x: 50, y: 50, width: 300, height: 300)
        textView.layer.borderColor = UIColor.gray.cgColor
        textView.layer.borderWidth = 1.0
        textView.layer.cornerRadius = 10.0
        view.addSubview(textView)
        
    }
    
    func Button() {
        let button = UIButton(frame: CGRect(x: 150, y: 700, width: 100, height: 100))
        button.backgroundColor = .orange
        button.addTarget(self, action: #selector(saveMemo), for: .touchUpInside)
        button.layer.cornerRadius = button.bounds.width / 2
        button.layer.masksToBounds = true
        view.addSubview(button)
    }

    func DatePicker() {
        let datePicker = UIDatePicker(frame: CGRect(x: 150, y: 300, width: 300, height: 300))
        datePicker.datePickerMode = UIDatePicker.Mode.date
        datePicker.timeZone = NSTimeZone.local
        datePicker.addTarget(self, action: #selector(picker(_:)), for: .valueChanged)
        view.addSubview(datePicker)
    }
    
    func DatePickerText() {
        datePickerText.frame = CGRect(x: 50, y: 500, width: 300, height: 100)
        datePickerText.backgroundColor = .white
        datePickerText.textAlignment = .center
        view.addSubview(datePickerText)
        
    }
    //MARK: -ActionFunction
    
    @objc func picker(_ sender: UIDatePicker) {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy/MM/dd"
        datePickerText.text = formatter.string(from: sender.date)
       
        view.addSubview(datePickerText)
        
    }
    //RealmDB書き込み処理
    @objc func saveMemo(){
        let realm = try! Realm()
        
        try! realm.write{
            // 未選択時に空文字を返す
            let Events = [EventModel(value: ["date": datePickerText.text ?? "", "event": textView.text ?? ""])]
            realm.add(Events)
            
        }
        
        print("DB register done")
        print(Realm.Configuration.defaultConfiguration.fileURL!)
        dismiss(animated: true, completion: nil)
    }
}


オブジェクト画面

import Foundation
import RealmSwift

class EventModel: Object {
    @objc dynamic var date: String = ""
    @objc dynamic var event: String = ""
    }


最後に

簡単ですが、シンプルな実装方法を紹介いたしました。
細かい解説については別途更新

ではまた。

コメント

タイトルとURLをコピーしました