Home > OS >  How to prevent a UITableViewCell from moving (Swift 5)
How to prevent a UITableViewCell from moving (Swift 5)

Time:02-26

This is actually a two part question. First take a look at the code:

//canEditRowAt
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    if tableView.tag == 1000{
        return indexPath.row == 0 ? false : true
        }
    return true
}

//canMoveRowAt
func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
    if tableView.tag == 1000{
        return indexPath.row == 0 ? false : true
    }
    return true
}

So from this I would expect that it would prevent the row at index 0 from having other cells move to it, but no... as you can see:

enter image description here

I obviously want to prevent it, but can't seem to find any documentation to solve the issue.

The other bit I'm struggling with; if you look at the recording you can see that once I move a cell into any location, a black bar appears behind the cell. I would like to avoid that from happening as well, and have tried several things but nothing has worked.

Any help is appreciated, thanks!

CodePudding user response:

To answer the first question, if you look at the tableView(_:canMoveRowAt:) UITableView reorder move UITableViewCell table view cell swift iOS

2. User a header view

This way you don't have to worry about specify any logic of which cells can move and which cannot as you can have the non movable data in a header view:

override func tableView(_ tableView: UITableView,
                        viewForHeaderInSection section: Int) -> UIView?
{
    if section == 0
    {
        // Customize any view
        let headerView = UIView(frame: CGRect(x: 0,
                                              y: 0,
                                              width: tableView.bounds.width,
                                              height: 100))
        headerView.backgroundColor = .red
        
        let label = UILabel(frame: headerView.bounds)
        label.text = "Header view"
        label.textColor = .white
        label.textAlignment = .center
        headerView.addSubview(label)
        
        return headerView
    }
    
    return nil
}

override func tableView(_ tableView: UITableView,
                        heightForHeaderInSection section: Int) -> CGFloat
{
    if section == 0
    {
        // specify any height
        return 100
    }
    
    return 0
}

UITableView custom header UIView swift iOS

I recommend the second option as it has the better user experience and seems to be the right way of approaching this problem.

To answer your second question, in your cellForRowAt indexPath or custom cell implementation, you probably set the background view of the cell or the contentView to black.

Try setting one of these or both:

cell.backgroundColor = .clear
cell.contentView.backgroundColor = .clear

This should not give you a black background

  • Related