ios UITableViewCell 多选时选择的背景颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26895370/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 03:36:23  来源:igfitidea点击:

UITableViewCell Selected Background Color on Multiple Selection

iosuitableviewswiftselectionselected

提问by Bogdan Bogdanov

// Doesn't work
cell.selectionStyle = .Blue
//Works when the selection is not multiple, if it's multiple with each selection the previous one disappear...
let cellBGView = UIView()
cellBGView.backgroundColor = UIColor(red: 0, green: 0, blue: 200, alpha: 0.4)
cell.selectedBackgroundView = cellBGView

Any answer how to set background color of the cells which are selected?

任何答案如何设置所选单元格的背景颜色?

采纳答案by Somoy Das Gupta

Swift 4.2

斯威夫特 4.2

For multiple selections you need to set the UITableViewproperty allowsMultipleSelectionto true.

对于多项选择,您需要将该UITableView属性设置allowsMultipleSelectiontrue

myTableView.allowsMultipleSelection = true

myTableView.allowsMultipleSelection = true

In case you subclassed the UITableViewCell, you override setSelected(_ selected: Bool, animated: Bool)method in your custom cell class.

如果您将UITableViewCell子类化,则您可以覆盖setSelected(_ selected: Bool, animated: Bool)自定义单元格类中的方法。

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

     if selected {
         contentView.backgroundColor = UIColor.green
     } else {
         contentView.backgroundColor = UIColor.blue
     }
 }

回答by OverD

All the above answers are fine but a bit to complex to my liking. The simplest way to do it is to put some code in the cellForRowAtIndexPath. That way you never have to worry about changing the color when the cell is deselected.

以上所有答案都很好,但在我看来有点复杂。最简单的方法是将一些代码放在cellForRowAtIndexPath. 这样您就不必担心在取消选择单元格时更改颜色。

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)

    /* this is where the magic happens, create a UIView and set its
       backgroundColor to what ever color you like then set the cell's
       selectedBackgroundView to your created View */

    let backgroundView = UIView()
    backgroundView.backgroundColor = YOUR_COLOR_HERE
    cell.selectedBackgroundView = backgroundView
    return cell
}

回答by D Kersnowski

This worked for me:

这对我有用:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    var selectedCell:UITableViewCell = tableView.cellForRowAtIndexPath(indexPath)!
    selectedCell.contentView.backgroundColor = UIColor.redColor()
}

// if tableView is set in attribute inspector with selection to multiple Selection it should work.

// Just set it back in deselect 

override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
    var cellToDeSelect:UITableViewCell = tableView.cellForRowAtIndexPath(indexPath)!
    cellToDeSelect.contentView.backgroundColor = colorForCellUnselected
}


//colorForCellUnselected is just a var in my class

回答by Ahmed Lotfy

Swift 3

斯威夫特 3

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

Swift 2

斯威夫特 2

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
     let cell = tableView.dequeueReusableCell(withIdentifier: "yourCellIdentifier", for: indexPath)
     cell.selectionStyle = .None
     return cell
}

回答by superarts.org

The problem with Kersnowski's approach is that when the cell is redrawn the changes made when it's selected/deselected will be gone. So I would move the changes into the cell itself, which means subclassing is required here. For example:

Kersnowski 方法的问题在于,重绘单元格时,选中/取消选中单元格时所做的更改将消失。所以我会将更改移动到单元格本身,这意味着这里需要子类化。例如:

class ICComplaintCategoryCell: UITableViewCell {
    @IBOutlet var label_title: UILabel!
    @IBOutlet var label_checkmark: UILabel!

    override func layoutSubviews() {
        super.layoutSubviews()
        reload()
    }
    func reload() {
        if isSelected {
            contentView.backgroundColor = UIColor.red
        }
        else if isHighlighted{
            contentView.backgroundColor = UIColor.red
        }
        else {
            contentView.backgroundColor = UIColor.white
        }
    }
}

And in your table view delegate just call reload:

在您的表视图委托中只需调用reload

if let cell = self.table.cellForRowAtIndexPath(path) as? ICComplaintCategoryCell {
    cell.reload()
}

Updated for Swift 3+, thanks @Bogy

为 Swift 3+ 更新,感谢 @Bogy

回答by Despotovic

You can also set cell's selectionStyleto.nonein interface builder. The same solution as @AhmedLotfy provided, only from IB.

您还selectionStyle可以.none在界面构建器中将单元格设置为。与@AhmedLotfy 提供的解决方案相同,仅来自 IB。

enter image description here

在此处输入图片说明

回答by Doci

For Swift 3,4 and 5 you can do this in two ways.

对于 Swift 3,4 和 5,您可以通过两种方式执行此操作。

1) class: UITableViewCell

1)类:UITableViewCell

override func awakeFromNib() {
    super.awakeFromNib()
    //Costumize cell

    selectionStyle = .none
}

or

或者

2) tableView cellForRowAt

2)tableView cellForRowAt

    cell.selectionStyle = .none

If you want to set selection color for specific cell, check this answer: https://stackoverflow.com/a/56166325/7987502

如果要为特定单元格设置选择颜色,请查看此答案:https: //stackoverflow.com/a/56166325/7987502

回答by SNudel

UITableViewCellhas an attribute multipleSelectionBackgroundView. https://developer.apple.com/documentation/uikit/uitableviewcell/1623226-selectedbackgroundview

UITableViewCell有一个属性multipleSelectionBackgroundViewhttps://developer.apple.com/documentation/uikit/uitableviewcell/1623226-selectedbackgroundview

Just create an UIViewdefine the .backgroundColorof your choice and assign it to your cells .multipleSelectionBackgroundViewattribute.

只需创建一个您选择的UIView定义.backgroundColor并将其分配给您的单元格.multipleSelectionBackgroundView属性。

回答by Barath

Swift 3

斯威夫特 3

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
     let selectedCell:UITableViewCell = tableView.cellForRow(at: indexPath)!
     selectedCell.contentView.backgroundColor = UIColor.darkGray
}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
     let selectedCell:UITableViewCell = tableView.cellForRow(at: indexPath)!
     selectedCell.contentView.backgroundColor = UIColor.clear
}

回答by Mr. JD Agrawal

By adding a custom view with the background color of your own you can have a custom selection style in table view.

通过添加具有您自己的背景颜色的自定义视图,您可以在表格视图中拥有自定义选择样式。

let customBGColorView = UIView()
customBGColorView.backgroundColor = UIColor(hexString: "#FFF900")
cellObj.selectedBackgroundView = customBGColorView

Add this 3 line code in cellForRowAt method of TableView. I have used an extension in UIColor to add color with hexcode. Put this extension code at the end of any Class(Outside the class's body).

在 TableView 的 cellForRowAt 方法中添加这 3 行代码。我在 UIColor 中使用了一个扩展来添加带有十六进制代码的颜色。将此扩展代码放在任何类的末尾(在类的主体之外)。

extension UIColor {    
convenience init(hexString: String) {
    let hex = hexString.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
    var int = UInt32()
    Scanner(string: hex).scanHexInt32(&int)
    let a, r, g, b: UInt32
    switch hex.characters.count {
    case 3: // RGB (12-bit)
        (a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
    case 6: // RGB (24-bit)
        (a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
    case 8: // ARGB (32-bit)
        (a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
    default:
        (a, r, g, b) = (255, 0, 0, 0)
    }
    self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
  }
}