Подтвердить что ты не робот

Пользовательский пользовательский интерфейс TableViewCell выбрал backgroundcolor swift

Я пытаюсь изменить внешний вид выбранного пользователем TableViewCell с помощью Swift.

Нужно ли это делать через дизайнера или программно?

Я попробовал следующее:

enter image description here

И вот мой код:

@IBOutlet var tableView: UITableView!


    var tableData: [String] = ["One", "Two", "Three", "Four"]

    override func viewDidLoad() {
        super.viewDidLoad()


        // Register custom cell
        var nib = UINib(nibName: "vwTblCell", bundle: nil)
        tableView.registerNib(nib, forCellReuseIdentifier: "cell")

    }

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

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell     {

        var cell:TblCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as TblCell

        cell.lblCarName.text = tableData[indexPath.row]
        cell.imgCarName.image = UIImage(named: tableData[indexPath.row])

        return cell

    }

    func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
        println("Row \(indexPath.row) selected")
    }

    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 70
    }
4b9b3361

Ответ 1

У вас уже есть правильный метод: didSelectRowAtIndexPath. В этом методе вы можете вызвать tableView.cellForRowAtIndexPath(indexPath) и получить свою ячейку. Чем вы можете установить цвет ячейки на свой цвет:

 func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
        println("Row \(indexPath.row) selected")
        let cell:YourCustomCell = tableView.cellForRowAtIndexPath(indexPath) as YourCell
        cell.backgroundColor = UIColor.redColor()
    }

Или лучший способ - проверить ваш метод cellForRowAtIndexPath, если выбрана ячейка:

if(cell.selected){
  cell.backgroundColor = UIColor.redColor()
}else{
  cell.backgroundColor = UIColor.clearColor()
}

Ответ 2

У меня проблема сходства. В вашем методе cellForRowAtIndexPath:

cell.selectionStyle = .None

а затем установите didHighlightRowAtIndexPath...

func tableView(tableView: UITableView, didHighlightRowAtIndexPath indexPath: NSIndexPath) {
    let cell  = tableView.cellForRowAtIndexPath(indexPath)
    cell!.contentView.backgroundColor = .redColor()
}

func tableView(tableView: UITableView, didUnhighlightRowAtIndexPath indexPath: NSIndexPath) {
        let cell  = tableView.cellForRowAtIndexPath(indexPath)
        cell!.contentView.backgroundColor = .clearColor()
}

Ответ 3

Мои два цента: правильный способ сделать это (также визуально) - использовать назначенный вид в ячейке (tableView), то есть свойство selectedBackgroundView. Однако сначала необходимо инициализировать его с помощью UIView()

SWIFT 3.0

override func awakeFromNib() {
    super.awakeFromNib()
    self.selectedBackgroundView = UIView()
    self.selectionStyle = .default // you can also take this line out
}

Затем вы можете использовать его в своей настраиваемой ячейке следующим образом:

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
    self.selectedBackgroundView!.backgroundColor = selected ? .red : nil
}

Что это. Разумеется, вы также можете интегрировать вышеуказанные функции UITableView, упомянутые выше. Проверьте это.

Ответ 4

Обновление для Swift 3

Этот ответ основан на ответе Cao Yong, и он предназначен как обновление для Swift 3

Для Swift 3 используйте следующий код в вашем методе cellForRowAt indexPath:

cell.selectionStyle = .none

Затем установите его в didHighlightRowAtIndexPath

func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
    let cell  = tableView.cellForRow(at: indexPath)
    cell!.contentView.backgroundColor = .red
}

func tableView(_ tableView: UITableView, didUnhighlightRowAt indexPath: IndexPath) {
    let cell  = tableView.cellForRow(at: indexPath)
    cell!.contentView.backgroundColor = .clear
}

Ответ 5

Когда вы нажимаете на ячейку, фоновый цвет субблоков фактически изменяется. Это подвью является "selectedBackgroundView". Вы можете переопределить представление каждой ячейки в методе делегата cellForRowAtIndexPath TableView.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

   let cell = tableView.dequeueReusableCellWithIdentifier("identifier", forIndexPath: indexPath) 

   let selectedView = UIView()
   selectedView.backgroundColor = UIColor(red: 250/255, green: 250/255, blue:     250/255, alpha: 1.0)
   cell.selectedBackgroundView = selectedView

   return cell
}

Измените цвет на все, что угодно.

Ответ 6

Чтобы ваш код был чистым, вы должны подумать о том, чтобы переместить код, связанный с экранированием, для ваших ячеек от UITableViewController в класс UITableViewCell.

Ваш UITableViewController` должен только установить выбранное состояние ячейки следующим образом:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
    guard let cell = tableView.cellForRow(at: indexPath) else { return }
    cell.setSelected(true, animated: true)
}

Ваша желаемая настройка может быть реализована в derrive UITableViewCell классе путем переопределения var isSelected. С помощью этого решения у вас могут быть разные цвета для каждой ячейки.

class MyTableViewCell: UITableViewCell
{
    @IBOutlet weak var label:UILabel!

    override var isSelected: Bool
    {
        didSet{
            if (isSelected)
            {
                self.backgroundColor = UIColor.red
                if let label = label
                {
                    label.textColor = UIColor.white
                }
            }
            else
            {
                self.backgroundColor = UIColor.white
                if let label = label
                {
                    label.textColor = UIColor.black
                }
            }
        }
    }
}

Ответ 7

Правильный (более естественный и естественный) способ сделать это:

override func awakeFromNib() {
    super.awakeFromNib()
    selectedBackgroundView = UIView()
    selectedBackgroundView?.backgroundColor = .blue
}

Почему другие подходы неправильны:

  1. Выделите решение: выделить не выбрать. Выделение не анимируется, как выделение. Это не кажется естественным, как нормальный отбор сделал бы
  2. Нет необходимости менять цвет selectedBackgroundView в методе setSelected, потому что iOS обрабатывает анимацию для нас.
  3. Настройка backgroundColor также не ведет себя так же, как iOS

Ответ 8

SWIFT 5 Обновление

Установите стиль выделения на .none в методе cellForRowAT:

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

    return cell
}

Затем реализуйте методы didHighlightRowAt и didUnhighlightRowAt:

func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
    let cell  = tableView.cellForRow(at: indexPath)
    cell!.contentView.backgroundColor = .red
}

func tableView(_ tableView: UITableView, didUnhighlightRowAt indexPath: IndexPath) {
    let cell  = tableView.cellForRow(at: indexPath)
    // Add timer to be able see the effect
    Timer.scheduledTimer(withTimeInterval: 0.2, repeats: false) { (_) in
       cell!.contentView.backgroundColor = .white
    }
}

Ответ 9


Для tableView ==


Первый вызов Этот метод -

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
        cell.textLabel?.text = "Show Label"
        cell.backgroundColor = UIColor.redColor()

    }

И чем вызов этого метода

func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
        cell.backgroundColor = UIColor.clearColor()
    }

Для CollectionView ==

1 -

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let cell = dateCollectionView.cellForItemAtIndexPath(indexPath) as! DateCollectionViewCell
            cell!.dateLabel.backgroundColor = UIColor.redColor()

 }  

2 -

func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
        let cell = dateCollectionView.cellForItemAtIndexPath(indexPath) as? DateCollectionViewCell
        cell!.dateLabel.backgroundColor = UIColor.clearColor()
    }