RealmとTableViewとFSCalendar 

# RealmとTableViewとFSCalendarのシンプルアプリ 

<img width="150" alt="62586C8E-D256-4735-9186-8E3296C0172C_1_201_a.jpeg" src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1466343/cc89b1fa-6496-83a5-4c9c-8bc7410e3663.jpeg"> <img width="150" alt="67E73CD8-28EC-4299-9E48-A415E0BDBF0F_1_201_a.jpeg" src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1466343/a5d6ad7b-4641-a99d-eab7-1f1a28160af1.jpeg"> <img width="153" alt="19DD446B-749A-4174-BB30-A24A9160E19E_1_201_a.jpeg" src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1466343/006da6e8-9e9b-32b8-c877-611b1c73e42b.jpeg"> <img width="153" alt="FF52AAD6-8AFB-4E50-81A2-35C86D0806E8_1_201_a.jpeg" src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1466343/331b90bc-624f-e102-95ae-9dd745e17502.jpeg">
今日作ったアプリもシンプルです。

# 簡単な機能説明
* カレンダーの下にあるボタンを押すと、モードを切り替えられます。ボタンの背景色が<font color="Blue">青色だとカレンダーの日付をタップしたらアラートを表示して予定を追加出来ます</font>。また、<font color="Red">赤色だとカレンダーの日付をタップしてもアラートは表示されず保存済みのデータを閲覧するだけの状態になります</font>。

#コードと簡単な解説

* Podfile 

```
pod 'FSCalendar'
pod 'CalculateCalendarLogic'  //今回は使用していません
pod 'RealmSwift'
``` 
# Model

* Realmに保存んする為のクラスの作成

```Swift:RealmDatas
import Foundation
import RealmSwift
 
class RealmDatas:Object{
    
    @objc dynamic var day = String()
    @objc dynamic var event = String()
    @objc dynamic var place = String()
    @objc dynamic var who = String()
    
}
```

* RealmCRUDModelに追加、取得機能を`extension`を用いて入力する
* カレンダー上のタップした日付を受け取り`filter`を用いた検索取得機能で必要な値だけ取得

```Swift:RealmCRUDModel
import Foundation
import RealmSwift

class RealmCRUDModel{
    
    var readRealmArray:[[String:String]] = []
    
}

extension RealmCRUDModel{
    
    func createRealm(createDay:String,createEvent:String,createPlace:String,createWho:String){
        
        do{
            let realm = try Realm()
            let realmDatas = RealmDatas()
            
            realmDatas.day = createDay
            realmDatas.event = createEvent
            realmDatas.place = createPlace
            realmDatas.who = createWho
            
            try realm.write({
                
                realm.add(realmDatas)
                
            })
        }catch{
            
            print(error.localizedDescription)
            
        }
    }
}

extension RealmCRUDModel{
    
    func readRealm(){
        
        do{
            let realm = try Realm()
            self.readRealmArray = []
            
            for readResult in realm.objects(RealmDatas.self){
                
                self.readRealmArray.append(["RealmEvent":readResult.event,"RealmPlace":readResult.place,"RealmWho":readResult.who])
                
            }
            
        }catch{
            
            print(error.localizedDescription)
            
        }
    }
}

extension RealmCRUDModel{
    
    func filterReadRealm(calendarDay:String){
        
        do{
            let realm = try Realm()
            self.readRealmArray = []
            
            for filterReadResult in realm.objects(RealmDatas.self).filter(NSPredicate(format: "day == %@", calendarDay)){
                
                self.readRealmArray.append(["RealmEvent":filterReadResult.event,"RealmPlace":filterReadResult.place,"RealmWho":filterReadResult.who])
                
            }
        }catch{
            
            print(error.localizedDescription)

        }  
    }
}
```
# Controller

* `@IBAction func modeChange(_ sender: Any){}` の中で追加機能と閲覧機能の切り替えを`UserDefaults`と`if文`を用いて書いています

```Swift:ViewController
import UIKit
import FSCalendar

class ViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var modeChangeButton: UIButton!
       
    let realmCRUDModel = RealmCRUDModel()
        
    override func viewDidLoad() {
        super.viewDidLoad()
      
        self.tableView.delegate = self
        self.tableView.dataSource = self
        
        UserDefaults.standard.set("追加", forKey: "addORLook")
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        self.modeChangeButton.layer.cornerRadius = 13.0
        
        self.careteCalendar()
        
    }

    @IBAction func modeChange(_ sender: Any) {
        
        if UserDefaults.standard.object(forKey: "addORLook") as! String == "追加" {
            
            self.modeChangeButton.setTitle("予定を追加可能にする", for: .normal)
            self.modeChangeButton.backgroundColor = .red
            UserDefaults.standard.set("見るだけ", forKey: "addORLook")
            
        }else{
                        
            self.modeChangeButton.setTitle("閲覧のみ状態にする", for: .normal)
            self.modeChangeButton.backgroundColor = .systemTeal
            UserDefaults.standard.set("追加", forKey: "addORLook")
           
        }       
    }
}
``` 

# View

* TableViewの各種設定

```Swift:TableView
import Foundation
import UIKit

extension ViewController:UITableViewDelegate,UITableViewDataSource{
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return 137
        
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        
        return 1
        
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return self.realmCRUDModel.readRealmArray.count
        
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        
        let cellEventLabel = cell.contentView.viewWithTag(1) as! UILabel
        let cellPlaceLabel = cell.contentView.viewWithTag(2) as! UILabel
        let cellWhoLabel = cell.contentView.viewWithTag(3) as! UILabel
        
        cellEventLabel.text = self.realmCRUDModel.readRealmArray[indexPath.row]["RealmEvent"]
        cellPlaceLabel.text = self.realmCRUDModel.readRealmArray[indexPath.row]["RealmPlace"]
        cellWhoLabel.text = self.realmCRUDModel.readRealmArray[indexPath.row]["RealmWho"]
        return cell
        
    }
}
```

* アラート機能

```Swift:Alert
import Foundation
import UIKit

extension ViewController{
    
    func createTextFieldAlert(calendarDay:String){

       var eventTextField:UITextField?
       var placeTextField:UITextField?
       var whoTextField:UITextField?
        
       let alert = UIAlertController(title: "追加確認アラート", message:"追加する場合は、値を入力して下さい", preferredStyle: .alert)

       alert.addTextField { (alertEventTextField:UITextField) in

        alertEventTextField.placeholder = "イベントなど"
            eventTextField = alertEventTextField

       }

       alert.addTextField { (alertPlaceTextField:UITextField) in

        alertPlaceTextField.placeholder = "どこで"
             placeTextField = alertPlaceTextField

       }
        
        alert.addTextField { (alertWhoTextField:UITextField) in
            
            alertWhoTextField.placeholder = "誰と"
            whoTextField = alertWhoTextField
            
        }

        alert.addAction(UIAlertAction(title: "キャンセル", style: .default, handler: { _ in
            
            self.realmCRUDModel.filterReadRealm(calendarDay: calendarDay)
            self.tableView.reloadData()
            
        }))
       
       alert.addAction(UIAlertAction(title: "追加", style: .default, handler: { _ in

        self.realmCRUDModel.createRealm(createDay: calendarDay, createEvent: (eventTextField?.text)!, createPlace: (placeTextField?.text)!, createWho: (whoTextField?.text)!)
           
        self.realmCRUDModel.filterReadRealm(calendarDay: calendarDay)
        self.tableView.reloadData()

        }))

        present(alert, animated: true, completion: nil)

   }   
}
```

* カレンダーの表示とカレンダーの日付をタップした時の処理

```Swift:Calendar
import Foundation
import FSCalendar
import UIKit

extension ViewController:FSCalendarDelegate,FSCalendarDataSource,FSCalendarDelegateAppearance{
    
    func careteCalendar(){
 
        let calendar = FSCalendar(frame: CGRect(x: 0, y: 88, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height/3.25))
        
        calendar.delegate = self
        calendar.dataSource = self
        
        self.view.addSubview(calendar)
        
    }
    
    func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) {
        
        let calendarDate = Calendar(identifier: .gregorian)
        let year = calendarDate.component(.year, from: date)
        let month = calendarDate.component(.month, from: date)
        let day = calendarDate.component(.day, from: date)
        
        if UserDefaults.standard.object(forKey: "addORLook") as! String == "追加" {
        
        createTextFieldAlert(calendarDay: "\(year)年\(month)月\(day)日")
     
        }else{
            
            self.realmCRUDModel.filterReadRealm(calendarDay: "\(year)年\(month)月\(day)日")
            self.tableView.reloadData()
            
        }       
    }   
}
```
# 終わり
ほとんどコードを載せているだけの状態なので、質問などはコメントまでお願いします。
指摘なども頂ければ嬉しいです。