I have a TableView with a playlist of music tracks. When I click on the row, the track starts to play and the current row is selected. Also, I have a search bar, which works fine. But if I click on the row, then on the search bar and then I finally on the Cancel button - the row with the current track is not selected. In other situations, like forward or backward playback, the selection of rows works well. Simplified, my code looks like this:
class TableView: UIViewController, UISearchResaultUpdating, UISearchBarDelegate {
...
private var currentSelectedRowIndex = 0
func ...didSelectRowAt indexPath... {
...
currentSelectedRowIndex = indexPath.row
print(currentSelectedRowIndex)
}
...
func searchCancelButtonClicked... {
print("Cancel button pressed")
print(currentSelectedRowIndex)
tableView.selectRow(at: IndexPath(row: currentSelectedRowIndex, section 0), animated: true, scrollPosition: .middle)
}
}
Console message:
1
Cancel button pressed
1
==========================
But the row is not selected, what's the problem?
If you look at the UITableView
documentation , it clearly says that calling selectRow
does not cause the delegate to receive tableView(_:didSelectRowAt:)
.
You can move whatever you are doing in tableView(_:didSelectRowAt:)
to another function and call that function in tableView(_:didSelectRowAt:)
and searchCancelButtonClicked
.
Or you can use the following code to manually invoke tableView(_:didSelectRowAt:)
in searchCancelButtonClicked
.
func searchCancelButtonClicked() {
print("Cancel button pressed")
print(currentSelectedRowIndex)
let indexPath = IndexPath(row: currentSelectedRowIndex, section: 0)
yourTableViewOutlet.delegate?.tableView?(yourTableViewOutlet, didSelectRowAt: indexPath)
tableView.selectRow(at: indexPath, animated: true, scrollPosition: .middle)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.