Egghead
Egghead

Reputation: 7017

show view only when uitableviecell is pressed

I have a UIViewController with a UITableView and an overlaying view. In the didSelectRowAtIndexPath the view is shown but I want it to hide as soon as the user lets go of the screen. So the view is only shown when the users presses a cell and hidden as soon as he lets go. I tried using touchesEnded but I can't get it to work.

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    self.colorView.hidden = false
    self.colorView.backgroundColor = colors[indexPath.row]

}

Any suggestions?

Upvotes: 0

Views: 84

Answers (2)

Cong Tran
Cong Tran

Reputation: 1458

You can use touchesEnded method on your TableViewCellto detect when user end touch on this cell. Then use delegate to send this event to your viewcontroller Here for example:

YourTableViewCell.swift

    protocol YourTableViewCellDelegate: class {
        func endTouch(indexPath: NSIndexPath)
    }


    class YourTableViewCell: UITableViewCell {
        weak var delegate: YourTableViewCellDelegate?
        var indexPath: NSIndexPath

       // Add Your Other method
        func bind(index: NSIndexPath) {
             self.indexPath = index
        }

        override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
            self.delegate?.endTouch(self.indexPath)
        }
    }

YourViewController.swift

class YourViewController: UIViewController, YourTableViewCellDelegate {

    // Add Your Other method

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        ...
            cell.delegate = self
            cell.bind(indexPath)
    }

    // MARK: - YourTableViewCellDelegate
    func endTouch(indexPath: NSIndexPath) {
        self.colorView.hidden = true
    }
}

Upvotes: 1

Urensoft
Urensoft

Reputation: 1

You should call colorView.hidden from your touches ended override.

override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {

        self.colorView.hidden = true
}

Upvotes: 0

Related Questions