Search code examples
swiftuitableviewcustom-celldidselectrowatindexpath

didSelectRowAt from custom cell do nothing


below code supposed to call usernames from an array and user able to tap on the desired username. call to that array is a success and I can see the usernames but won't able to tap into it. and it don't even print "didSelectRowAt". appreciate your help. thanks.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellIdentifier", for: indexPath) as! MentionUserCell

    cell.username!.text = autoComplete[indexPath.row]

    return cell
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
    return autoComplete.count
}



func numberOfSections(in tableView: UITableView) -> Int
{
    return 1
}


func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{

    let selectedCell: MentionUserCell = tableView.cellForRow(at: indexPath)! as! MentionUserCell
    let selectedWord: String = selectedCell.username!.text! + " "
    print("didSelectRowAt")
    var string: NSString = NSString(string: self.commentTextView.text!)
    string = string.replacingCharacters(in: otoCadang.sharedInstance.foundRange, with: selectedWord) as NSString

    // change text field value
    commentTextView.text = string as? String

    // change cursor position
    let positionOriginal = commentTextView.beginningOfDocument
    if let cursorLocation: UITextPosition = self.commentTextView.position(from: positionOriginal, offset: otoCadang.sharedInstance.foundRange.location + selectedWord.characters.count)
    {
        self.commentTextView.selectedTextRange = self.commentTextView.textRange(from: cursorLocation, to: cursorLocation)
    }



    // remove suggestion
    self.autoComplete.removeAll()
    self.tableView.reloadData()
    tableView.isHidden = true
}

Solution

  • Check List

    1. tableview delegate is set properly
    2. tableview selection mode == No Selection, then change to single selection
    3. function name is correct func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    4. are you using any tap gesture on this view? remove it.