[英]Custom UI TableViewCell selected backgroundcolor swift
I am trying to change the appearance of a custom selected TableViewCell using Swift.我正在尝试使用 Swift 更改自定义选定 TableViewCell 的外观。
Do I need to do it via the designer or programmatically?我需要通过设计器还是以编程方式来完成?
I tried the following:我尝试了以下方法:
And here is my code:这是我的代码:
@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
}
I have a likeness problem.我有一个肖像问题。 In your cellForRowAtIndexPath method set:在您的cellForRowAtIndexPath方法集中:
cell.selectionStyle = .None
and then set didHighlightRowAtIndexPath ...然后设置didHighlightRowAtIndexPath ...
func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
cell!.contentView.backgroundColor = .green
}
func tableView(_ tableView: UITableView, didUnhighlightRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
cell!.contentView.backgroundColor = .clear
}
My two cents: the proper way of doing it (also visually) is to use the designated view in a (tableView)cell, that is the selectedBackgroundView property.我的两分钱:正确的做法(也是在视觉上)是在 (tableView) 单元格中使用指定的视图,即 selectedBackgroundView 属性。 However, you need to initialize it first with UIView()但是,您需要先使用 UIView() 对其进行初始化
SWIFT 3.0斯威夫特 3.0
override func awakeFromNib() {
super.awakeFromNib()
self.selectedBackgroundView = UIView()
self.selectionStyle = .default // you can also take this line out
}
Then you can use it in your customized cell as follows:然后您可以在您的自定义单元格中使用它,如下所示:
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
self.selectedBackgroundView!.backgroundColor = selected ? .red : nil
}
That's it.就是这样。 Of course you can also integrate the above in your UITableView functions referred to above.当然,您也可以将上述内容集成到上面提到的 UITableView 函数中。 Check it out.一探究竟。
You've the right method already in there: didSelectRowAtIndexPath
.您已经有了正确的方法: didSelectRowAtIndexPath
。 In that method you can call tableView.cellForRowAtIndexPath(indexPath)
and get your cell.在该方法中,您可以调用tableView.cellForRowAtIndexPath(indexPath)
并获取您的单元格。 Than you can set the cell-background to your color:比您可以将单元格背景设置为您的颜色:
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
println("Row \(indexPath.row) selected")
let cell:YourCustomCell = tableView.cellForRowAtIndexPath(indexPath) as YourCell
cell.backgroundColor = UIColor.redColor()
}
Or, a better way would be to check in your cellForRowAtIndexPath
method, if a cell is selected:或者,如果选择了一个单元格,更好的方法是检查您的cellForRowAtIndexPath
方法:
if(cell.selected){
cell.backgroundColor = UIColor.redColor()
}else{
cell.backgroundColor = UIColor.clearColor()
}
Update for Swift 3 Swift 3更新
This answer is based on Cao Yong answer, and it is intended as an update for Swift 3此答案基于曹勇的答案,旨在作为Swift 3的更新
For Swift 3 , use the following code in your cellForRowAt indexPath method set:对于Swift 3 ,请在cellForRowAt indexPath方法集中使用以下代码:
cell.selectionStyle = .none
Then, set it in didHighlightRowAtIndexPath然后,在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
}
override func awakeFromNib() {
super.awakeFromNib()
selectedBackgroundView = UIView()
selectedBackgroundView?.backgroundColor = .blue
}
Why other approaches are wrong:为什么其他方法是错误的:
setSelected
method, because iOS handles the animation for us.无需在setSelected
方法中更改 selectedBackgroundView 的颜色,因为 iOS 为我们处理动画。backgroundColor
also doesn't behave the same as iOS does it设置backgroundColor
行为也与 iOS 不同When you tap a cell, a subviews background color is actually being changed.当您点击一个单元格时,实际上正在更改子视图背景颜色。 That subview is 'selectedBackgroundView'.该子视图是“selectedBackgroundView”。 You can override the view of each cell in the cellForRowAtIndexPath TableView delegate method.您可以在 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
}
Change the color to whatever you like.将颜色更改为您喜欢的任何颜色。
To keep your code clean you should think about moving screen design related code for your cells from UITableViewController
into a UITableViewCell
class.为了保持代码整洁,您应该考虑将单元格的屏幕设计相关代码从UITableViewController
到UITableViewCell
类中。
Your UITableViewController` needs only to set the selected state of the cell as follows:你的 UITableViewController` 只需要设置单元格的选中状态如下:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
guard let cell = tableView.cellForRow(at: indexPath) else { return }
cell.setSelected(true, animated: true)
}
Your desired customisation can be implemented in a derrived UITableViewCell
class by overriding var isSelected
.您可以通过覆盖var isSelected
在派生的UITableViewCell
类中实现您想要的自定义。 With this solution you could have even different select colors for each cell.使用此解决方案,您甚至可以为每个单元格选择不同的颜色。
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
}
}
}
}
}
SWIFT 5 Update SWIFT 5 更新
Set the selection style to .none in the cellForRowAT
method:在cellForRowAT
方法中将选择样式设置为 .none:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! Cell
cell.selectionStyle = .none
return cell
}
Then implement the didHighlightRowAt
and the didUnhighlightRowAt
methods:然后实现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
}
}
First Call This method-首先调用此方法-
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()
}
And than call this method而不是调用这个方法
func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
cell.backgroundColor = UIColor.clearColor()
}
For CollectionView==对于集合视图==
1- 1-
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let cell = dateCollectionView.cellForItemAtIndexPath(indexPath) as! DateCollectionViewCell
cell!.dateLabel.backgroundColor = UIColor.redColor()
}
2- 2-
func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
let cell = dateCollectionView.cellForItemAtIndexPath(indexPath) as? DateCollectionViewCell
cell!.dateLabel.backgroundColor = UIColor.clearColor()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
updateUI(isSelected: selected)
}
private func updateUI(isSelected: Bool){
label.textColor = isSelected ? .red : .green
//etc..
}
None of above answers worked, so I try mine and it worked: Here it is:-以上答案都没有奏效,所以我尝试了我的,并且奏效了:这是:-
func reloadcell() {
if isSelected {
conView.backgroundColor = .yellow
} else if isHighlighted {
conView.backgroundColor = .yellow
} else {
conView.backgroundColor = .clear
}
}
and call that function in layoutsubviews and in your didselect method并在 layoutsubviews 和 didselect 方法中调用该函数
In your cellForRowAtIndexPath method set:在您的 cellForRowAtIndexPath 方法集中:
cell.selectionStyle = .none
and then set didHighlightRowAtIndexPath like this...然后像这样设置 didHighlightRowAtIndexPath ......
func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
cell!.contentView.backgroundColor = .green
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.