Search code examples
iosswiftuitableviewtextlabel

TextLabel colour automatically changed when i Scroll UiTableView


I changing textlabel color on didSelectRowAt but when I scroll UITableView it also effects in other textlabel also

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
 let cell = tableView.cellForRow(at: indexPath) as! TableViewCell


    if (cell.LBLIntrest.textColor == (UIColor.black))
    {
         cell.LBLIntrest.textColor = Uicolor.blue
    } else {
          cell.LBLIntrest.textColor = Uicolor.black
    }
}

Solution

  • First you have to create property to hold selected cell like below

    /* To hold selected cell */
    var selectedIndexPath :IndexPath?
    

    After that set color of selected cell in cellForRowAt

     override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
        if let cell = tableView.dequeueReusableCell(withIdentifier: "cell") {
            cell.textLabel?.text = "Row Number: \(indexPath.row)"
    
            /* Check if cell is selected then set layout accourding to your requirements */
            if indexPath == selectedIndexPath {
                cell.textLabel?.textColor = .blue
            } else {
                cell.textLabel?.textColor = .black
            }
            return cell
        }
    
        return UITableViewCell()
    }
    

    After this manage when user select a cell in didSelectRowAt

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        // Toggle if user seleted same cell
        if selectedIndexPath == indexPath {
            if let cell = tableView.cellForRow(at: indexPath) {
                /* Check and toggle selected cell color */
                cell.textLabel?.textColor = cell.textLabel?.textColor == .black ? .blue : .black
            }
        } else {
            /* set color of seleted cell */
            if let cell = tableView.cellForRow(at: indexPath) {
                cell.textLabel?.textColor = .blue
            }
        }
    
        /* Save which cell is selected */
        selectedIndexPath = indexPath
    }
    

    And last manage didDeselectRowAt

    override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    
        /* Remove if deselect same cell */
        if selectedIndexPath == indexPath {
            selectedIndexPath = nil
        }
         /* Change color to black */
        if let cell = tableView.cellForRow(at: indexPath) {
            cell.textLabel?.textColor = .black
        }
    }
    

    This code is for on cell selection at one time so you have to set

    tableView.allowsMultipleSelection = false
    

    Hope this helps.