Make tableview cells not selectable but tableview still scrollable

2107 views ios
5

I would like to make the cells of a tableView non-selectable but still allow scrolling. When I placed

 tableView.isUserInteractionEnabled = false

which is recommended in some answers in viewDidLoad, it prevents selection but also prevents scrolling.

Adding:

 cell.selectionStyle = .none

in cellforrowatindexpath as below not have any effect for me.

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        self.tableView.beginUpdates()
        self.tableView.endUpdates()

        if let cell = tableView.dequeueReusableCell(withIdentifier: "myMessageCell", for: indexPath) as? myMessageCell {
            cell.message = messages[indexPath.row]
            cell.selectionStyle = .none
        }

        return tableView.dequeueReusableCell(withIdentifier: "myMessageCell", for: indexPath)
    }

Can anyone suggest how to prevent selection without preventing scrolling?

Thanks in advance for any suggestions.

answered question

What is happening when you select the cell now? The color changes? That should be fixed is you set the selectionStyle to .none

"did not have any effect for me"? What effect where you expecting? What happened?

The cell gets highlighted or not. Will add more code above. I was expecting it to not change color e.g. highlight.

Why self.tableView.beginUpdates(), self.tableView.endUpdates()?

Also, if you know reuseIdentifier "myMessageCell" will always return a myMessageCell, this is an appropriate place to use as! myMessageCell. There's probably an issue in your storyboard that force unwrapping will uncover.

Ok. I am just learning Swift so still getting my head around optionals. Begin and endUpdates was an effort to get cells to autoresize based on content that is still unsolved.

2 Answers

5

Hope you are looking for this one:

tableView.allowsSelection = false

posted this
13

The problem is you are not returning the same cell that you are dequeuing. Instead you are dequeuing another cell and returning it which has none of the properties that you have set.

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    if let cell = tableView.dequeueReusableCell(withIdentifier: "myMessageCell", for: indexPath) as? myMessageCell {
        cell.message = messages[indexPath.row]
        cell.selectionStyle = .none
        return cell // Return the cell here instead
    }

    // return tableView.dequeueReusableCell(withIdentifier: "myMessageCell", for: indexPath) // Return another cell which has none of your properties set.
    return UITableViewCell() // return default cell in case your cell is not dequeued
}

posted this

Have an answer?

JD

Please login first before posting an answer.