TextLabel colour automatically changed when i Scroll UiTableView

前端 未结 2 688
名媛妹妹
名媛妹妹 2021-01-27 06:04

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

func ta         


        
2条回答
  •  南笙
    南笙 (楼主)
    2021-01-27 06:45

    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.

提交回复
热议问题