UITableViewCell Выбранный цвет фона при множественном выделении
// Doesn't work
cell.selectionStyle = .Blue
//Works when the selection is not multiple, if it 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
Любой ответ, как установить цвет фона выделенных ячеек?
Ответы
Ответ 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
}
}
Ответ 2
Все приведенные выше ответы являются хорошими, но немного сложными по моему вкусу. Самый простой способ сделать это - добавить код в 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
}
Ответ 3
Это сработало для меня:
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
Ответ 4
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
}
Ответ 5
Проблема с подходом 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
}
}
}
А в вашем табличном представлении делегат просто вызовите reload
:
if let cell = self.table.cellForRowAtIndexPath(path) as? ICComplaintCategoryCell {
cell.reload()
}
Обновлено для Swift 3+, спасибо @Bogy
Ответ 6
Вы также можете установить ячейку selectionStyle
в .none
в построителе интерфейса. То же решение, что и @AhmedLotfy, предоставляется только от IB.
![введите описание изображения здесь]()
Ответ 7
Для Swift 3,4 и 5 вы можете сделать это двумя способами.
1) класс: UITableViewCell
override func awakeFromNib() {
super.awakeFromNib()
//Costumize cell
selectionStyle = .none
}
или
2) tableView cellForRowAt
cell.selectionStyle = .none
Имейте в виду, это отключит функцию didSelectCell, что означает, что выбор ячейки не будет запускать никаких действий для этой ячейки.
Ответ 8
UITableViewCell
имеет атрибут multipleSelectionBackgroundView
. https://developer.apple.com/documentation/uikit/uitableviewcell/1623226-selectedbackgroundview
Просто создайте UIView
определите .backgroundColor
по вашему выбору и назначьте его своим ячейкам .multipleSelectionBackgroundView
.
Ответ 9
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
}
Ответ 10
Добавляя пользовательский вид с собственным цветом фона, вы можете иметь собственный стиль выбора в табличном представлении.
let customBGColorView = UIView()
customBGColorView.backgroundColor = UIColor(hexString: "#FFF900")
cellObj.selectedBackgroundView = customBGColorView
Добавьте этот трехстрочный код в метод cellForRowAt TableView. Я использовал расширение в UIColor, чтобы добавить цвет с помощью hexcode. Поместите этот код расширения в конец любого класса (вне тела класса).
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)
}
}
Ответ 11
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
}
}
}
Ответ 12
Вы можете использовать стандартные методы 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 раза на выбранную ячейку, следует выполнить дальнейшую навигацию.
Ответ 13
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
}
}