Zizoo Zizoo - 3 months ago 13
Swift Question

How to manipulate UITableViewCell after another cell is tapped ? - Swift

How to manipulate

UITableViewCell
after another cell is tapped ?

I have 3 cells each one has
UIPickerView
the first cell's
userInteractionEnabled
is
true
but the 2nd and 3rd is
false
.. when the user tap the 1st cell the rest of cells's
userInteractionEnabled
should be
true


I know I need to use
userInteractionEnabled
but how ? should I hold the cells in variables then manipulate when I need to?

Answer

I've read solutions above and are all valid of course, but I prefer a solution like this: I suppose you have an array of object to display (ignoring pattern you're using).

class MyObject: NSObject {
   var selected: Bool = false
}

class MyViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var objects: [MyObject] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        // init your objects: 
        // 1stObj.enabled = true
        // 2ndObj.enabled = false
        // 3rdObj.enabled = false
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
         let obj = self.objects[indexPath.row]
         let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
         cell.userInteractionEnabled = obj.enabled
         return cell
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        for obj in self.objects {
           obj.selected = !obj.selected
        } 
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        tableView.reloadData()
    }
}

I think this solution is more scalable and maintainable, but is my opionion.

update

For manipulate cell outside of 'cellForRowAtIndexPath' function, you can do in this way for instance:

func manuallyModifyCell(atIndex index: Int, backgroundColor: UIColor = .clearColor()) {
    let indexPath = NSIndexPath(forRow: index, inSection: 0)
    if let cell = tableView.cellForRowAtIndexPath(indexPath) {
        cell.backgroundColor = backgroundColor
    }
}
Comments