Search code examples
backgroundswiftuicontextmenu

SwiftUI - context menu background colour


Context menu background not updated

I am trying to update background colour.

Background colour is updated for view, but it is not getting updated for the context menu

Context menu shows previous colour which was set.

can someone help me with this. thanks in advance

this is the code i used

import SwiftUI

struct ContextMenu: View {
    /*List of items =*/

    @State var bgColor = Color.gray
    var body: some View {

        HStack {
            Rectangle().frame(width: 120, height: 120).opacity(0.01).border(Color.black, width: 1).contextMenu{
                VStack {
                    Button("Orange",action: {
                        self.bgColor = Color.orange
                    })

                    Button("Green",action: {
                        self.bgColor = Color.green
                    })

                    Button("Red",action: {
                        self.bgColor = Color.red
                    })
                }
            }
        }.frame(width:UIScreen.main.bounds.width, height: 200).background(bgColor)

    }
}

Solution

  • Context menu caches content and reuse it all the time. Here is possible solution to force update it.

    Tested with Xcode 11.4 / iOS 13.4

    demo

    HStack {
        Rectangle().fill(bgColor) // << use same color
            .frame(width: 120, height: 120)
            .border(Color.black, width: 1)
            .contextMenu{
                VStack {
                    Button("Orange",action: {
                        self.bgColor = Color.orange
                    })
    
                    Button("Green",action: {
                        self.bgColor = Color.green
                    })
    
                    Button("Red",action: {
                        self.bgColor = Color.red
                    })
                }
            }.id(UUID())      // << force recreate context menu
    }.frame(width:UIScreen.main.bounds.width, height: 200).background(bgColor)