3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

RealmとTableViewとFSCalendar

Last updated at Posted at 2021-07-11

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

62586C8E-D256-4735-9186-8E3296C0172C_1_201_a.jpeg 67E73CD8-28EC-4299-9E48-A415E0BDBF0F_1_201_a.jpeg 19DD446B-749A-4174-BB30-A24A9160E19E_1_201_a.jpeg FF52AAD6-8AFB-4E50-81A2-35C86D0806E8_1_201_a.jpeg
今日作ったアプリもシンプルです。

簡単な機能説明

  • カレンダーの下にあるボタンを押すと、モードを切り替えられます。ボタンの背景色が青色だとカレンダーの日付をタップしたらアラートを表示して予定を追加出来ます。また、赤色だとカレンダーの日付をタップしてもアラートは表示されず保存済みのデータを閲覧するだけの状態になります

#コードと簡単な解説

  • Podfile
pod 'FSCalendar'
pod 'CalculateCalendarLogic'  //今回は使用していません
pod 'RealmSwift'

Model

  • Realmに保存んする為のクラスの作成
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を用いた検索取得機能で必要な値だけ取得
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){} の中で追加機能と閲覧機能の切り替えをUserDefaultsif文を用いて書いています
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の各種設定
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
        
    }
}
  • アラート機能
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)

   }   
}
  • カレンダーの表示とカレンダーの日付をタップした時の処理
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()
            
        }       
    }   
}

終わり

ほとんどコードを載せているだけの状態なので、質問などはコメントまでお願いします。
指摘なども頂ければ嬉しいです。

3
4
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
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?