SwiftUI:为 .toolbar ToolbarItem 设置单独的颜色? [英] SwiftUI: Setting individual colors for .toolbar ToolbarItem?

查看:24
本文介绍了SwiftUI:为 .toolbar ToolbarItem 设置单独的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一般来说,出于可访问性的原因,我喜欢坚持使用默认颜色选项,但我有一个特定的用例,我无法更改单个 .toolbar ToolbarItem 颜色.

Generally I like to stick with default color options for accessibility reasons, but I have a specific use case and I am unable to change an individual .toolbar ToolbarItem color.

我可以使用代码段顶部注释掉的代码覆盖所有 ToolbarItem 颜色,但我想为单个图标着色.

I can override all ToolbarItem colors by using the commented out code at top of my snippet, but I want to color individual icons.

import SwiftUI

struct ContentView: View {
    
//    init() {
//        UIBarButtonItem.appearance(whenContainedInInstancesOf: [UIToolbar.self]).tintColor = .systemRed
//    }
    
    var body: some View {
        
        NavigationView {
            
            Text("Hello, world!")
                .toolbar {
                    
                    // To be colored RED
                    ToolbarItem(placement: .bottomBar) {
                        Button(action: {}, label: {Label("Icon One", systemImage: "stop.fill")})
                    }
                    
                    // To be colored BLACK
                    ToolbarItem(placement: .bottomBar) {
                        Button(action: {}, label: {Label("Icon Two", systemImage: "play.fill")})
                    }
                    
                }
        }
    }
}

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

推荐答案

看起来所有标准类型(按钮、图像、文本等)都被 ToolbarItem 拦截并转换为适当的内部表示.但是自定义视图(例如基于形状)......不是.因此,请参阅下面的可能方法演示.

It looks like all standard types (button, image, text, etc) are intercepter by ToolbarItem and converted into appropriate internal representation. But custom view (eg. shape based)... is not. So see below a demo of possible approach.

演示准备&使用 Xcode 12/iOS 14 进行测试.

Demo prepared & tested with Xcode 12 / iOS 14.

ToolbarItem(placement: .bottomBar) {
    ShapeButton(shape: Rectangle(), color: .red) {
        print(">> works")
    }
}

和简单的基于形状的自定义按钮

and simple custom Shape-based button

struct ShapeButton<S:Shape>: View {
    var shape: S
    var color: Color
    var action: () -> ()

    @GestureState private var tapped = false
    var body: some View {
        shape
            .fill(color).opacity(tapped ? 0.4 : 1)
            .animation(.linear(duration: 0.15), value: tapped)
            .frame(width: 18, height: 18)
            .gesture(DragGesture(minimumDistance: 0)
                .updating($tapped) { value, state, _ in
                    state = true
                }
                .onEnded { _ in
                    action()
                })
    }
}

这篇关于SwiftUI:为 .toolbar ToolbarItem 设置单独的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆