滚动UiTableView时TextLabel颜色自动更改 [英] TextLabel colour automatically changed when i Scroll UiTableView

查看:101
本文介绍了滚动UiTableView时TextLabel颜色自动更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我更改了didSelectRowAt上的文本标签颜色,但是当我滚动UITableView时,它也影响了其他textlabel

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
    }
}

推荐答案

首先,您必须创建属性来保存选定的单元格,如下所示:

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

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

之后,在 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()
}

此后,当用户在 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
}

最后一次管理 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

希望这会有所帮助.

这篇关于滚动UiTableView时TextLabel颜色自动更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆