How to tune performance with ButtonBehavior in SwiftUI

Issue #779

With Xcode 12.4, macOS 11.0 app. Every time we switch the system dark and light mode, the CPU goes up to 100%. Instruments show that there’s an increasing number of ButtonBehavior

Screenshot 2021-02-24 at 10 12 05

Suspect State in a row in LazyVStack

Every cell has its own toggle state

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
struct Cell: View {
enum ToggleState {
case general
case request
case response
}

let item: Item
@State
private var toggleState: ToggleState = .general

func toggleButton(text: String, state: ToggleState) -> some View {
Button(action: { self.toggleState = state }) {
Text(text)
.foregroundColor(state == toggleState ? Color.label : Color.secondary)
.fontWeight(state == toggleState ? .bold : .regular)
}
.buttonStyle(BorderlessButtonStyle())
}
}

Removing the buttons fix the problem. The workaround is to use Text with onTapGesture

1
2
3
4
5
6
Text(text)
.foregroundColor(state == toggleState ? Color.label : Color.secondary)
.fontWeight(state == toggleState ? .bold : .regular)
.onTapGesture {
self.toggleState = state
}

Updated at 2021-02-24 10:10:41

Comments