SwiftUIカンニングペーパー: Binding, ListとButtonなどなど

Howto

やった事あるけど思い出せないし、時間をかけたくない時のカンニングペーパー + アウトプット

SwiftUIカンニングペーパー: Binding, ListとButtonなどなど

@Stateと@Bindingとinit

  • @Binding は外部から渡される値の参照です。
  • 初期化: 初期値は不要で、init またはビューの本体内で外部からバインディングされた値を受け取ります。
  • スコープ: 複数のビュー間でデータを共有する場合によく使用されます。

struct ParentView: View {
    @State private var text = "Hello, World!"
    
    var body: some View {
        MyDetailView(text: $text)
    }
}

struct MyDetailView: View {
    @Binding var text: String
    
    init(text: Binding<String>) {
        _text = text
    }
    
    var body: some View {
        Text(text)
    }
}

肝になるところ

親:

  • @Stateを使い
  • 渡すときは$を先頭に付加。

子:

  • @Baindingを使い、初期化の必要はないが値がどう渡されているのかを少し考える
  • init(Binding< >で受け取る。
  • init()内で、_を受け取る変数の先頭に付加

子にinit()が無ければ単純なのですが。


ListとButtonでタップ感知範囲が広すぎ問題

SwiftUIのListButtonが同時にタップを検出する問題は、特にListNavigationLinkや他のインタラクティブ要素と一緒に使用されるときによく発生します。

解決法: .buttonStyle(PlainButtonStyle())

Button.buttonStyle(PlainButtonStyle())を適用することで、Buttonが親ビューのタップジェスチャを引き継がないようにすることができます。

Button(action: {
    addSchedule(productItem: item)
}, label: {
    Text("スケジュール編集")
})
.buttonStyle(PlainButtonStyle())

CoreDataリレーションシップのPredicate

対1の場合

NSPredicate(format: "resident == %@ AND productItem == %@", resident, productItem)

対多の場合

NSPredicate(format: "residents CONTAINS %@", resident)

Viewの高さを画面の半分にする

    .frame(height: UIScreen.main.bounds.height / 2)

 VStack {
            Text("ScheduleEditer")

            Spacer()
        }
        .frame(height: UIScreen.main.bounds.height / 2)
}

感想: 覚えるの苦手

CoreData: UIKit と SwiftUI で共存させる際に、同じコンテナやエンティティを使う場合、いくつか注意すべき点

-com.apple.CoreData.ConcurrencyDebug 1


if Thread.isMainThread {
    // メインスレッドで実行されるコード
} else {
    // バックグラウンドスレッドで実行されるコード
}
assert(Thread.isMainThread, "This is not on the main thread")

コメント

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