Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

    }
}
like image 900
Ramachandiran J A Avatar asked Apr 10 '26 04:04

Ramachandiran J A


1 Answers

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)
like image 184
Asperi Avatar answered Apr 12 '26 08:04

Asperi