0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【SwiftUI】でピン留め機能を実装する

Posted at

🗒 はじめに
SwiftUIでリストを作るとき、「特定の項目を上に固定したい」「お気に入りを目立たせたい」
そんなときに便利なのが ピン留め機能 です📌
この記事では、
SwiftUIでのピン留め切り替え
CoreDataで状態を保存する(簡単に)
の2点を実装していきます。
CoreDataは永続化のために軽く使うだけで、メインはピン留めの仕組みです。

🎯 完成イメージ
ピンボタンを押すと、項目が上に移動
再起動してもピン状態が保持される
ピン付きは淡い黄色で背景表示

💡 ピン留めの考え方
ピン留めの基本はシンプルです👇
各アイテムに isPinned フラグを持たせる
ボタンタップで isPinned.toggle()
表示時に isPinned == true のアイテムを上にソート
永続化には CoreData を使いますが、
考え方自体はどのデータモデルでも同じです。

🧱 モデル構成(CoreData)
CoreDataのエンティティ(例:Memo)を以下のように作成します。

属性名 備考
id UUID 主キー
title String タイトル
body String 内容
date Date 作成日
isPinned Boolean ピン留め状態(デフォルト: false)

🧠 ViewModel
ピンのトグルと削除、保存処理を行います。
スクリーンショット 0007-10-20 0.05.48.png

📋 View側の実装(MemoListView)
スクリーンショット 0007-10-20 0.07.39.png
スクリーンショット 0007-10-20 0.08.22.png

✅ 完成イメージ
Simulator Screenshot - iPhone 15 Pro Max - 2025-10-20 at 00.11.23.png

🪄 ここがポイント
✅ ピン付きメモが常に上にくるのは、sortDescriptors で isPinned を優先してるから。
✅ ピン状態は CoreData に保存されるので、アプリ再起動しても維持。
✅ 背景色を変えて「固定されている感」を出すと視覚的にもわかりやすい。

🔚 まとめ
ピン留めは、
Booleanフラグ
トグルアクション
ソート指定
の3つを組み合わせるだけで簡単に実現できます。
CoreDataを使えば状態を永続化できるため、
メモアプリ・ToDoアプリなどで「重要な項目を固定したい」ときに非常に便利です📌

0
1
1

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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?