[英]How to fix: func selectRow in the TableView does not work when I click Cancel in search bar
I have a TableView with a playlist of music tracks.我有一个带有音乐曲目播放列表的 TableView。 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:)
.如果您查看
UITableView
文档,它清楚地表明调用selectRow
不会导致委托接收tableView(_:didSelectRowAt:)
。
You can move whatever you are doing in tableView(_:didSelectRowAt:)
to another function and call that function in tableView(_:didSelectRowAt:)
and searchCancelButtonClicked
.您可以将您在
tableView(_:didSelectRowAt:)
中所做的任何事情移动到另一个 function 并在tableView(_:didSelectRowAt:)
和 searchCancelButtonClicked 中searchCancelButtonClicked
。
Or you can use the following code to manually invoke tableView(_:didSelectRowAt:)
in searchCancelButtonClicked
.或者您可以使用以下代码在
searchCancelButtonClicked
中手动调用tableView(_:didSelectRowAt:)
。
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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.