SwiftUI ForEach コード例

SwiftUI ForEach

SwiftUIにはForEachという構造体(struct)があります。このForEachIdentifiedデータを用いてオンデマンドでViewを再構築してくれます。ForEachイニシャライザにidパラメータを提供する必要があります。

数字をカウントさせてTextに埋める場合のコード例

var body: some View {
	VStack{
		ForEach(0..<10){_i in
			Text("\(_i)")
		}
	}
}

文字配列を使ったForEachコード例

var body: some View {
	VStack{
		ForEach(["不思議の国のトムキンス","すばらしい新世界"], id: \.self){
			Text($0)
		}
	}
}

Identifiable構造体の配列を使ったForEachコード例

struct Hoge: Identifiable{ 
    var id = UUID()
    var value : String
}

上記のようなIdentifiable継承したstructを使った配列はForEachで利用可能です

struct ContentView: View {
    @State var hogeList:[Hoge] = [Hoge(value: "Aldous Leonard Huxley"),Hoge(value: "James Patrick Hogan")]
    var body: some View {
        VStack{
            ForEach(hogeList){_i in
                let hoge: String = _i.value
                Text("\(hoge)")
            }
        }
    }
}

Swift NSSavePanelで Thread 1: EXC_BREAKPOINT

NSSavePanel runModal()

Swift macOS App デフォルトプロジェクトで、NSSavePanel()を使った場合Thread 1: EXC_BREAKPOINT が出て下記のようなエラーが表示されます。

[OpenSavePanels] ERROR: Unable to display save panel: your app has the User Selected File Read entitlement but it needs User Selected File Read/Write to display save panels. Please ensure that your app's target capabilities include the proper entitlements.

Sandboxの設定が「User Selected File = ReadOnly」になっているので「Read / Write」に変更すれば解決します。

User selected file read write
User Selected File = Read / Write

一度でもビルドに成功していてUser Selected File = ReadOnlyに変更した場合下記のメッセージが出ます

error: Entitlements file "xxx.entitlements" was modified during the build, which is not supported. You can disable this error by setting 'CODE_SIGN_ALLOW_ENTITLEMENTS_MODIFICATION' to 'YES', however this may cause the built product's code signature or provisioning profile to contain incorrect entitlements. (in target 'xxx' from project 'xxx')

2022 MJELD TECHNOLOGIES. ALL RIGHTS RESERVED