SwiftUI:如何更改警报按钮和NavigationLink后退按钮的颜色?

时间:2020-10-03 15:41:45

标签: swift swiftui

如何从警报中的按钮和导航链接中的后退按钮更改颜色?在“警报”按钮中的文本后设置.accentColor(.init("someColor"))无效。在NavigationLink之后设置.accentColor(.init("someColor"))也不起作用。我该怎么办?

警报按钮: enter image description here

NavigationLink中的“后退”按钮: enter image description here

struct ContentView: View {
    
    @State var showSheet = false
    @State var alertShouldBeShown = !UserDefaults.standard.bool(forKey: "£Start")

    var body: some View {
        Button(action:  {
            self.showSheet.toggle()
        }) {
            Text("click me")
            //.accentColor(colorScheme == .dark ? Image("") : Image("Info-Icon"))
        }.sheet(isPresented: $showSheet) {
            SheetView(showSheet: self.$showSheet)
        }
        .alert(isPresented: $alertShouldBeShown, content: {

            Alert(title: Text("Headline"),
                message: Text("Text"),
                dismissButton: Alert.Button.default(
                    Text("Ok"), action: {
                    UserDefaults.standard.set(true, forKey: "Start")
                    }
                )
            )
        })
    }
}

struct SheetView: View {
    @Binding var showSheet: Bool
    var body: some View {
        NavigationView {
            DetailView()
                .navigationBarTitle(Text("Headline"), displayMode: .inline)
                .navigationBarItems(trailing: Button(action: {
                    self.showSheet = false
                }) {
                    Text("Done")
                        .bold()
            })
        }.navigationViewStyle(StackNavigationViewStyle())
    }
}

struct DetailView: View {
    var body: some View {
        List {
            HStack {
                NavigationLink(destination: DetailViewOne()) {
                                    Text("View 1")
                }
            }
            HStack {
                NavigationLink(destination: DetailViewTwo()) {
                                    Text("View 2")
                }
            }
        }
    }
}

struct DetailViewOne: View {
    var body: some View {
        Text("1")
    }
}

struct DetailViewTwo: View {
    var body: some View {
        Text("2")
    }
}

1 个答案:

答案 0 :(得分:1)

您可以使用accentColor来更改NavigationBar的强调色,但需要将其应用于SheetView(给定环境的根视图):

SheetView(showSheet: self.$showSheet)
    .accentColor(.red)

不幸的是,到目前为止,SwiftUI尚未允许Alert进行很多自定义。

不过,由于Alert构建在UIKit组件(UIAlertController之上),这也意味着您可以更改UIView外观,当它们包含在{ {1}}。

您可以将此代码放在您的@main App初始化或SceneDelegate中:

UIAlertController