Joe Joe - 2 months ago 11
Swift Question

TableView didSelect respond issue in Swift

I have a tableView running in my project successfully.But,I have a problem selecting cell and updating my textView which connected to tableview in the same viewController.My textView only updating when i do a long press on tableViewCell.I want to update textView everytime when cell been pressed.I believe,when i pressed the cell deselect itself. My partial code as follow..

Note:
I am using the below code in my different projects that works with no issue..I am not sure whats wrong with this tableview....

Thanks in Advance....

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let CellIdentifier: String = "fontCell"
let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier, forIndexPath: indexPath)

let fontName: String = self.fontName[indexPath.row] as! String

UIView.animateWithDuration(1, delay: 0, usingSpringWithDamping: 0.3, initialSpringVelocity: 0.5, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in

cell.textLabel?.text = fontName
cell.textLabel!.font = UIFont(name: self.fontName[indexPath.row] as! String, size: 25)

}, completion: nil)

cell.backgroundColor = UIColor.clearColor()
cell.textLabel?.textAlignment = .Center
cell.textLabel?.textColor = UIColor.whiteColor()
cell.textLabel?.sizeToFit()
cell.textLabel?.adjustsFontSizeToFitWidth = true
cell.selectionStyle = .Default

return cell
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//tableView.deselectRowAtIndexPath(indexPath, animated: true)

dispatch_async(dispatch_get_main_queue(), { () -> Void in
let fontName: String = self.fontName[indexPath.row] as! String

self.textView.font = UIFont(name: fontName, size: 20)
})

}

Answer

didSelectRowAtIndexPath should already be called on the main thread so removing the dispatch_async and just running the code like this should be fine

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let fontName: String = self.fontName[indexPath.row] as! String
    self.textView.font = UIFont(name: fontName, size: 20)
}

If you've added a gesture recognizer to your tableView to handle long press (or something else) that might be interfering with your other taps. try setting cancelsTouchesInView to false on your recogniser.

tapGestureRecognizer.cancelsTouchesInView = false