SwiftUI:如何为 iPhone 显示一些工具栏按钮

问题描述

我有一组工具栏按钮,只有在设备是 iPhone(不是 iPad)时才应该显示

以下代码失败并出现此错误

包含控制流语句的闭包不能与结果构建器“ToolbarContentBuilder”一起使用

我确实理解它失败的原因,但我无法想出一个解决方案来实现我的需要。

import SwiftUI

struct ContentView: View {
    var body: some View {
        NavigationView {
            List {
                NavigationLink(
                    destination: Hello(),label: {
                        Text("Hello")
                    })
            }
        }
    }
}

struct Hello: View {
    var body: some View {
        Text("Hello World")
            .toolbar() {
                if UIDevice.current.userInterfaceIdiom == .phone {
                    ToolbarItem(placement: .navigationBarTrailing) {
                        Button(action: {
                            // do something
                        },label: {
                            Text("Button1")
                        })
                    }
                    ToolbarItem(placement: .navigationBarTrailing) {
                        Button(action: {
                            // do something
                        },label: {
                            Text("Button2")
                        })
                    }
                }
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button(action: {
                        // do something
                    },label: {
                        Text("Button3")
                    })
                }
            }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

我很高兴创建一个单独的函数来实现它。我简直不知道该怎么做。

解决方法

可能你想要这个

struct Hello: View {
    var body: some View {
        Text("Hello World")
            .toolbar() {
                ToolbarItemGroup(placement: .navigationBarTrailing) {
                    if UIDevice.current.userInterfaceIdiom == .phone {
                        Button(action: {
                            // do something
                        },label: {
                            Text("Button1")
                        })
                        Button(action: {
                            // do something
                        },label: {
                            Text("Button2")
                        })
                    }
                    Button(action: {
                        // do something
                    },label: {
                        Text("Button3")
                    })
                }
            }
    }
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...