Цвет фона меняется автоматически в Multiple Cell Selection Swift - PullRequest
0 голосов
/ 30 октября 2018

У меня есть вид таблицы. Я использую несколько ячеек выбора. Все работает правильно, функциональность - мудрая, но интерфейс - нет. Всякий раз, когда я выбираю ячейку и прокручиваю вниз, я вижу, что цвет меняется в другой ячейке ниже, хотя эта ячейка никогда не была выбрана. Я сделал это для клетки:

class FollowSportsCell: UITableViewCell {

@IBOutlet weak var sportL: UILabel!
@IBOutlet weak var backImg: UIImageView!

override func awakeFromNib() {

    super.awakeFromNib()
}

override func setSelected(_ selected: Bool, animated: Bool) {

    super.setSelected(selected, animated: animated) 
}

override func prepareForReuse() {

    super.prepareForReuse()

    backImg.backgroundColor = UIColor(hexString: "E6E6E6")

    sportL.textColor = .black


}

А вот и делегаты.

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return sportsArr!.count

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell                   = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath) as!                                                                         FollowSportsCell

    let sport                 = sportsArr![indexPath.row]["id"] as! Int

    cell.sportL.text      = sportsArr![indexPath.row]["title"] as? String

    cell.selectionStyle = UITableViewCell.SelectionStyle.none

    if selectedSports.contains(sport) {

        cell.sportL.textColor = .white

        cell.backImg.backgroundColor = UIColor(hexString: "4293CC")

    }

    return cell

}

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

    selectedCell += 1

    let sport = sportsArr![indexPath.row]["id"]

    selectedSports.append(sport! as! Int)

    if selectedCell > 1
    {
        collectionB[0].backgroundColor = UIColor(hexString: "4293CC")

        collectionB[0].isEnabled               = true
    }

}

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

    selectedCell -=  1

    selectedSports = selectedSports.filter{$0 != sportsArr![indexPath.row]["id"] as! Int}

    if selectedCell < 2
    {
        collectionB[0].backgroundColor = .lightGray

        collectionB[0].isEnabled               =  false
    }

}

Когда число низкое, например 4 или 5, и свиток не появляется, все хорошо, но как только они равны 20-22, я получаю эту проблему. Любая помощь?

Ответы [ 3 ]

0 голосов
/ 30 октября 2018

Вы должны обрабатывать цвет фона в tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath). Проверьте и используйте приведенный ниже код. Надеюсь, это сработает

 var selectedCells = Array<NSInteger>()

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return sportsArr!.count

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell             = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath) as! FollowSportsCell

    cell.sportL.text     = sportsArr![indexPath.row]["title"] as? String

    cell.selectionStyle  = UITableViewCell.SelectionStyle.none

    if self.selectedCells.contains(indexPath.row) {
        cell.sportL.textColor = .white

        cell.backImg.backgroundColor = UIColor(hexString: "4293CC")

        if self.selectedCells.count > 1
        {
            collectionB[0].backgroundColor = UIColor(hexString: "4293CC")

            collectionB[0].isEnabled               = true
        }
    }
    else
    {
        //Here Set your default color for cell backImgr background color
        cell.sportL.textColor = // set default color

            cell.backImg.backgroundColor = // set default color

    }
    return cell

}

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

    let cell = tableView.cellForRow(at: indexPath) as! FollowSportsCell

    if self.selectedCells.contains(indexPath.row) {
        //Here you will get selected cell and going to deselect...Do anything with deselection

        if let index = self.selectedCells.index{$0 == indexPath.row}
        {
          self.selectedCells.remove(at: index)
        }

        cell.sportL.textColor = .black

        cell.backImg.backgroundColor = UIColor(hexString: "E6E6E6")

        selectedCell -=  1

        selectedSports = selectedSports.filter{$0 != sportsArr![indexPath.row]["id"] as! Int}

        if self.selectedCells.count < 2
        {
            collectionB[0].backgroundColor = .lightGray

            collectionB[0].isEnabled               =  false
        }

    }
    else
    {
        self.selectedCells.append(indexPath.row)
        print(cell.sportL.text!)

        selectedCell += 1

        let sport = sportsArr![indexPath.row]["id"]

        selectedSports.append(sport! as! Int)
    }

    self.yourtblView.reloadData()



}
0 голосов
/ 30 октября 2018
import UIKit

class TableVC: UIViewController,UITableViewDelegate,UITableViewDataSource {

    @IBOutlet weak var tableView : UITableView!

   var arrayOfTitle : [titleOfArray] = [titleOfArray]()

   override func viewDidLoad() {
        super.viewDidLoad()

        if self.tableView != nil {
            self.tableView.delegate = self
            self.tableView.dataSource = self
        }

        for i in 0...20 {
            self.arrayOfTitle.append(titleOfArray(title: "Test\(i)", isSelectedIndex: false))
        }

        // Do any additional setup after loading the view.
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

        return 80
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return self.arrayOfTitle.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = self.tableView.dequeueReusableCell(withIdentifier: "cell")
        cell?.textLabel!.text = self.arrayOfTitle[indexPath.row].title
        cell?.textLabel!.textColor =  self.arrayOfTitle[indexPath.row].isSelectedIndex ? UIColor.red : UIColor.blue
        return cell!
    }

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

        for i in 0...self.arrayOfTitle.count-1 {
            self.arrayOfTitle[i].isSelectedIndex = false
        }
        self.arrayOfTitle[indexPath.row].isSelectedIndex = true
        tableView.reloadData()
    }
}


class titleOfArray : NSObject {

    var title : String!
    var isSelectedIndex : Bool!

    init(title:String! ,isSelectedIndex :Bool) {

        self.title = title
        self.isSelectedIndex = isSelectedIndex
    }
}

это может быть полезно

0 голосов
/ 30 октября 2018

Пожалуйста, выберите ваш по умолчанию и выбранный цвет в "CellForRowAtIndexPAth". Пожалуйста, проверьте код ниже.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell             = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath) as! FollowSportsCell
    cell.sportL.text     = sportsArr![indexPath.row]["title"] as? String
    cell.selectionStyle  = UITableViewCell.SelectionStyle.none

    let sport = sportsArr![indexPath.row]["id"]
    cell.sportL.textColor = default cell colour
    cell.backImg.backgroundColor = default cell colour


    if selectedSports.contain(sport) {
            cell.sportL.textColor = required cell colour
            cell.backImg.backgroundColor = required cell colour

    }
    return cell

    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...