When you tap a row in a UITableView, the row is highlighted and selected. Is it possible to disable this so tapping a row does nothing?
Yes, it's possible to disable the highlighting and selection of a row in a UITableView
in iOS when a user taps on it. You can achieve this by implementing the UITableViewDelegate
method tableView(_:didSelectRowAt:)
and not taking any action inside it.
Here's an example in Swift:
swift
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
let data = ["Item 1", "Item 2", "Item 3"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = data[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// Disable row selection by not doing anything here
}
}
In this example:
- We have a
UITableView
with three rows and data to display. - We set the view controller as the delegate and data source for the table view.
- We implement the
tableView(_:didSelectRowAt:)
method but leave its body empty, effectively doing nothing when a row is selected.
With this implementation, when a user taps a row in the table view, it won't be highlighted or selected because we've overridden the default behavior of the didSelectRowAt
method. This allows you to control what happens when a row is tapped without any automatic selection or highlighting.
Comments
Post a Comment