The selected row remains grey after navigating back from the detail view. Happening both on simulator and real device, only on iOS 14. Does anyone know how to remove it so it behaves the same as on iOS 13 (doesn't remain selected)? This is the only code in the project. (No other navigation's or anything).
let items = ["item1", "item2"]
struct ContentView: View {
var body: some View {
NavigationView {
VStack {
Text("Hello")
List(items, id: \.self) { item in
NavigationLink(destination: Text(item)) {
Text(item)
}
}
.listStyle(PlainListStyle())
}
}
// .navigationViewStyle(StackNavigationViewStyle()) // didn't solve the problem
}
}
This is how it looks
This is the trick. Just create a ZStack and put an empty button above.
var body: some View {
List {
ForEach(data, id: \.self) { item in
ZStack {
Button("") {}
NavigationLink(destination: ItemView(item: item)) {
ItemRow(item: item)
}
}
}
}
}
I had the same problem as soon as I used StackNavigationViewStyle()
.
The issue resolved itself for me by using DefaultNavigationViewStyle()
.
Here is the way I made it work. I have found some very rare cases where there is a bit of a lag for the highlight to disappear, but so far it helped a lot. This example uses the MVVM pattern, hopefully you get the idea.
You can access the underlying UITableView behind the SwiftUI List with this third party library :
https://github.com/siteline/SwiftUI-Introspect
and then you can store the tableView instance, and flush the selection when the table appears and disappears (somehow it worked better to do it in both, as those blocks may execute with a bit of lag depending on how aggressively the user navigates)
List {
// ...
}
.introspectTableView { tableView in
self.viewModel.bindToTableView(tableView)
}
.onAppear(perform: {
self.viewModel.clearTableViewSelection()
})
.onDisappear(perform: {
self.viewModel.clearTableViewSelection()
})
And in the viewModel, here are the functions
func bindToTableView(_ tableView: UITableView) {
self.tableView = tableView
}
func clearTableViewSelection() {
// This is a iOS14 hack that prevents clicked cell background view to remain highlighted when we come back to the screen
if #available(iOS 14, *){
DispatchQueue.main.async {
if let selectedIndexPath = self.tableView?.indexPathForSelectedRow {
self.tableView?.deselectRow(at: selectedIndexPath, animated: false)
if let selectedCell = self.tableView?.cellForRow(at: selectedIndexPath) {
selectedCell.setSelected(false, animated: false)
}
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With