UITableViewCell多选的选定背景颜色

时间:2014-11-12 19:52:32

标签: ios uitableview swift selection selected

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

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

13 个答案:

答案 0 :(得分:70)

这对我有用:

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

答案 1 :(得分:33)

Swift 3

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

Swift 2

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

答案 2 :(得分:12)

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

lifecycleCallbacks:
    prePersist: [ prePersist ]
    preUpdate:  [ preUpdate ]

在您的表格视图中,委托只需致电public function preUpdate() { ... $this->setChanged(new \DateTime()); ... }

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

更新了Swift 3+,感谢@Bogy

答案 3 :(得分:3)

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

enter image description here

答案 4 :(得分:2)

  

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

答案 5 :(得分:2)

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

1)class:UITableViewCell

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

    selectionStyle = .none
}

2)tableView cellForRowAt

    cell.selectionStyle = .none

答案 6 :(得分:1)

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

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

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

答案 7 :(得分:1)

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

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

答案 8 :(得分:1)

Swift 4.2

对于多项选择,您需要将UITableView属性allowsMultipleSelection设置为 true

  

myTableView.allowsMultipleSelection = true

如果您将 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
    }
}

答案 9 :(得分:1)

Swift 5-这对我有用:

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

        let selectedCell:UITableViewCell = tableView.cellForRow(at: indexPath as IndexPath)!
        selectedCell.contentView.backgroundColor = .red
    }



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

        let cellToDeSelect:UITableViewCell = tableView.cellForRow(at: indexPath as IndexPath)!
        cellToDeSelect.contentView.backgroundColor = .clear
    }

答案 10 :(得分:0)

SWIFT 3/4

CustomCell.selectionStyle = .none的解决方案,如果您设置其他样式,则会看到灰色或蓝色的“混合”背景色。

别忘了! func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath)没打CustomCell.selectionStyle = .none

extension MenuView: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cellType = menuItems[indexPath.row]
        let selectedCell = tableView.cellForRow(at: indexPath)!
            selectedCell.contentView.backgroundColor = cellType == .none ? .clear : AppDelegate.statusbar?.backgroundColor?.withAlphaComponent(0.15)

        menuItemDidTap?(menuItems[indexPath.row])

        UIView.animate(withDuration: 0.15) {
            selectedCell.contentView.backgroundColor = .clear
        }
    }
}

答案 11 :(得分:0)

您可以使用标准的UITableViewDelegate方法

- (nullable NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    EntityTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    [cell selectMe];
    return indexPath;
}

- (nullable NSIndexPath *)tableView:(UITableView *)tableView willDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    EntityTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    [cell deSelectMe];
    return indexPath;
}

在我的情况下,这可行,因为我们需要选择单元格,更改颜色,并且当用户在选定的单元格上轻按2次时,应进一步导航。

答案 12 :(得分:-1)

Swift 4

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

如果要取消选择上一个单元格,也可以使用不同的逻辑

var tempcheck = 9999
var lastrow = IndexPath()
var lastcolor = UIColor()
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
    if tempcheck == 9999
    {
        tempcheck = 0
        let selectedCell = tableView.cellForRow(at: indexPath)! as! HealthTipsCell
        lastcolor = selectedCell.contentView.backgroundColor!
        selectedCell.contentView.backgroundColor = UIColor.blue
        lastrow = indexPath
    }
    else
    {
        let selectedCelllasttime = tableView.cellForRow(at: lastrow)! as! HealthTipsCell
        selectedCelllasttime.contentView.backgroundColor = lastcolor
        let selectedCell = tableView.cellForRow(at: indexPath)! as! HealthTipsCell
        lastcolor = selectedCell.contentView.backgroundColor!
        selectedCell.contentView.backgroundColor = UIColor.blue
        lastrow = indexPath
    }
}