點擊 TableView 可視範圍外的 Button(如側欄頭像),觸發 TableView 內部**最後一行 Cell 的選中效果並執行對應邏輯**(類似 CSDN App 側欄頭像跳轉)。
tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none)didSelectRowAt 代理方法。tableView.delegate?.tableView?(tableView, didSelectRowAt: indexPath)@IBAction func headerButtonTapped(_ sender: UIButton) {
let lastSection = tableView.numberOfSections - 1
let lastRow = tableView.numberOfRows(inSection: lastSection) - 1
guard lastRow >= 0 else { return }
let indexPath = IndexPath(row: lastRow, section: lastSection)
// 1. 視覺上選中(可選 animated 滾動)
tableView.selectRow(at: indexPath, animated: true, scrollPosition: .middle)
// 2. 手動觸發 delegate 方法執行業務邏輯
tableView.delegate?.tableView?(tableView, didSelectRowAt: indexPath)
}
// delegate 實現
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// 取消高亮(可選)
tableView.deselectRow(at: indexPath, animated: true)
// 業務跳轉
navigateToDetail(for: indexPath)
}
scrollPosition: .middle/.top 會自動滾動使其可見;若不想滾動用 .none。tableView.allowsSelection = true,且 Cell selectionStyle != .none 才有高亮效果。此模式完美解耦「外部觸發」與「內部選中邏輯」,符合 iOS 代理設計模式。