LoginSignup
0
0

More than 1 year has passed since last update.

Realmからデータを取得してUISegmentedControlに表示

Posted at

こんな感じです

ED4F4636-0DF1-4CDA-B3AA-2D1ED1F18E90_1_201_a.jpeg

コードと簡単解説

  • let realm = try Realm()でRealm()のインスタンスを作成します

  • for文でrealm.objects(RealmDataSets.self)で取得したRealmの値をreadRealmTagに入れます。

  • realmTagArray.allSatisfyでreadRealmTagの値がrealmTagArrayの全ての値に、同じものがないのなら、realmTagArray.append(readRealmTag.tag)で配列に値を追加します。

  • 同じタイトルのSegmentができない様に、realmTagArrayの中に同じ値が入らない様にしています。

           ~~~一部省略~~~

var realmTagArray = [String]()

func readRealmTag(){

        do{
            let realm = try Realm()
            realmTagArray = []

            for readRealmTag in realm.objects(RealmDataSets.self){

                if realmTagArray.allSatisfy({$0 != readRealmTag.tag}) == true{

                    realmTagArray.append(readRealmTag.tag)

                }

            }

        }catch{

            //エラー処理など
        }
    }
  • .removeAllSegments()でSegmentを削除出来ます。(新しいSegmentを作る際に、以前作成したSegmentが残ってると古いSegmentの上に新しいSegmentが表示されてしまい、変な見た目になります。)

  • エラー回避のためにrealmCRUDModel.realmTagArray.countが0の時はSegmentを作成させない様にします。

  • UISegmentedControl()は簡単にですがこちらで解説しました。Buttonを押すとSegmentが増える(UISegmentedControl)


           ~~~一部省略~~~


var uiSegmentControl = UISegmentedControl()
let realmCRUDModel = RealmCRUDModel()

func createSegment(targetView:UIView){

        realmCRUDModel.readRealmTag()

        uiSegmentControl.removeAllSegments()

        if realmCRUDModel.realmTagArray.count != 0{

           for segmentCount in 0...realmCRUDModel.realmTagArray.count - 1{

                uiSegmentControl.insertSegment(withTitle: realmCRUDModel.realmTagArray[segmentCount], at: segmentCount, animated: true)

           }
        }

        uiSegmentControl.frame = CGRect(x: targetView.bounds.minX + 5, y: targetView.bounds.minY + 97, width: targetView.frame.size.width - 10, height: 32)

        uiSegmentControl.selectedSegmentTintColor = UIColor(red: 1.0, green: 0.40, blue: 0.51, alpha: 1.0)

        targetView.addSubview(uiSegmentControl)
    }

終わり

最近、作っているアプリからの内容でした。

ご指摘、ご質問などありましたら、コメントまでお願い致します。

0
0
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
0
0