Why are my tableVeiws Rows so Jumpy while scrolling? - ios

Below is the code of my tableView controller which takes an image from a UIImage array resizes it to aspect ratio and displays it on screen. While I scroll the images are very choppy? Is there anyway to reduce the choppiness?
import UIKit
class TableViewController: UITableViewController {
var images = imagePost.defaultimages //An array of a class containing images
var indexPathPass = IndexPath(row: 0, section: 0)
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 100
tableView.backgroundColor = colors.backgroundColor
DispatchQueue.main.async {
self.tableView.scrollToRow(at: self.indexPathPass, at: .top, animated: false)
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableViewCell
// Configure the cell...
cell.cellImageView.image = self.images[indexPath.row].image
cell.cellImageView.image = cell.cellImageView.image?.resizeImageWith()
cell.backgroundColor = UIColor(displayP3Red: 0, green: 20, blue: 1, alpha: 0.99)
cell.layer.shouldRasterize = true
return cell
}
override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
}

Check for the difference in your estimatedRowHeight and the actualRowHeight, the more is the difference the more it will jump while scrolling.

Solution 1.
If possible, try to implement 'heightForItem at indexPath' method. And return calculated height
Solution 2.
You can implement height caching mechanism. Like below code.
class TableViewController: UITableViewController {
var images = imagePost.defaultimages //An array of a class containing images
var indexPathPass = IndexPath(row: 0, section: 0)
fileprivate var cachedHeight = [IndexPath: CGFloat]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 100
tableView.backgroundColor = colors.backgroundColor
DispatchQueue.main.async {
self.tableView.scrollToRow(at: self.indexPathPass, at: .top, animated: false)
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableViewCell
// Configure the cell...
cell.cellImageView.image = self.images[indexPath.row].image
cell.cellImageView.image = cell.cellImageView.image?.resizeImageWith()
cell.backgroundColor = UIColor(displayP3Red: 0, green: 20, blue: 1, alpha: 0.99)
cell.layer.shouldRasterize = true
return cell
}
override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return cachedHeight[indexPath] ?? 100
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cachedHeight[indexPath] = cell.frame.height
}
}

Related

Background colours changing automatically in Multiple Cell Selection Swift

I have a table view. I am using multiple cell selection. Everything is working correctly, functionality wise, but UI wise it is not. Whenever I select a cell and scroll down I see the color is changed in another cell below though that cell was never actually selected. What I have done is this for the cell:
class FollowSportsCell: UITableViewCell {
#IBOutlet weak var sportL: UILabel!
#IBOutlet weak var backImg: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
override func prepareForReuse() {
super.prepareForReuse()
backImg.backgroundColor = UIColor(hexString: "E6E6E6")
sportL.textColor = .black
}
And, here are delegates.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sportsArr!.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath) as! FollowSportsCell
let sport = sportsArr![indexPath.row]["id"] as! Int
cell.sportL.text = sportsArr![indexPath.row]["title"] as? String
cell.selectionStyle = UITableViewCell.SelectionStyle.none
if selectedSports.contains(sport) {
cell.sportL.textColor = .white
cell.backImg.backgroundColor = UIColor(hexString: "4293CC")
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedCell += 1
let sport = sportsArr![indexPath.row]["id"]
selectedSports.append(sport! as! Int)
if selectedCell > 1
{
collectionB[0].backgroundColor = UIColor(hexString: "4293CC")
collectionB[0].isEnabled = true
}
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
selectedCell -= 1
selectedSports = selectedSports.filter{$0 != sportsArr![indexPath.row]["id"] as! Int}
if selectedCell < 2
{
collectionB[0].backgroundColor = .lightGray
collectionB[0].isEnabled = false
}
}
When, the number is low like 4 or 5 and the scroll doesn't appear everything is good, but once they are like 20-22 then, I get this issue. Any help?
You should handle background color in tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) .
Check and use below code. Hope it will work
var selectedCells = Array<NSInteger>()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sportsArr!.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath) as! FollowSportsCell
cell.sportL.text = sportsArr![indexPath.row]["title"] as? String
cell.selectionStyle = UITableViewCell.SelectionStyle.none
if self.selectedCells.contains(indexPath.row) {
cell.sportL.textColor = .white
cell.backImg.backgroundColor = UIColor(hexString: "4293CC")
if self.selectedCells.count > 1
{
collectionB[0].backgroundColor = UIColor(hexString: "4293CC")
collectionB[0].isEnabled = true
}
}
else
{
//Here Set your default color for cell backImgr background color
cell.sportL.textColor = // set default color
cell.backImg.backgroundColor = // set default color
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! FollowSportsCell
if self.selectedCells.contains(indexPath.row) {
//Here you will get selected cell and going to deselect...Do anything with deselection
if let index = self.selectedCells.index{$0 == indexPath.row}
{
self.selectedCells.remove(at: index)
}
cell.sportL.textColor = .black
cell.backImg.backgroundColor = UIColor(hexString: "E6E6E6")
selectedCell -= 1
selectedSports = selectedSports.filter{$0 != sportsArr![indexPath.row]["id"] as! Int}
if self.selectedCells.count < 2
{
collectionB[0].backgroundColor = .lightGray
collectionB[0].isEnabled = false
}
}
else
{
self.selectedCells.append(indexPath.row)
print(cell.sportL.text!)
selectedCell += 1
let sport = sportsArr![indexPath.row]["id"]
selectedSports.append(sport! as! Int)
}
self.yourtblView.reloadData()
}
Please select your default and selected color in "CellForRowAtIndexPAth". Please check the below code.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath) as! FollowSportsCell
cell.sportL.text = sportsArr![indexPath.row]["title"] as? String
cell.selectionStyle = UITableViewCell.SelectionStyle.none
let sport = sportsArr![indexPath.row]["id"]
cell.sportL.textColor = default cell colour
cell.backImg.backgroundColor = default cell colour
if selectedSports.contain(sport) {
cell.sportL.textColor = required cell colour
cell.backImg.backgroundColor = required cell colour
}
return cell
}
import UIKit
class TableVC: UIViewController,UITableViewDelegate,UITableViewDataSource {
#IBOutlet weak var tableView : UITableView!
var arrayOfTitle : [titleOfArray] = [titleOfArray]()
override func viewDidLoad() {
super.viewDidLoad()
if self.tableView != nil {
self.tableView.delegate = self
self.tableView.dataSource = self
}
for i in 0...20 {
self.arrayOfTitle.append(titleOfArray(title: "Test\(i)", isSelectedIndex: false))
}
// Do any additional setup after loading the view.
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 80
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.arrayOfTitle.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "cell")
cell?.textLabel!.text = self.arrayOfTitle[indexPath.row].title
cell?.textLabel!.textColor = self.arrayOfTitle[indexPath.row].isSelectedIndex ? UIColor.red : UIColor.blue
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
for i in 0...self.arrayOfTitle.count-1 {
self.arrayOfTitle[i].isSelectedIndex = false
}
self.arrayOfTitle[indexPath.row].isSelectedIndex = true
tableView.reloadData()
}
}
class titleOfArray : NSObject {
var title : String!
var isSelectedIndex : Bool!
init(title:String! ,isSelectedIndex :Bool) {
self.title = title
self.isSelectedIndex = isSelectedIndex
}
}
this might be helpful

UICollectionView inside UITableview, table should display dynamic value, no fix value is there. How to generate this?

I have a UICollectionView inside a UITableView.
Just like this image
There are 3categories and under each category, there is some content. I did this using tag value. But if I want dynamic category, then how to populate?
Here is my code:
import UIKit
class ViewController: UIViewController {
var categories = ["Revitalize", "Focus","Motivation"]
var revitalImages: [UIImage] = [UIImage(named: "revitalize1.png")!, UIImage(named: "revitalize2.png")!, UIImage(named: "revitalize3.png")!, UIImage(named: "revitalize4.png")!]
var focusImages: [UIImage] = [UIImage(named: "focus1.png")!, UIImage(named: "focus2.png")!, UIImage(named: "focus3.png")!, UIImage(named: "focus4.png")!]
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.tableView.separatorStyle = UITableViewCellSeparatorStyle.none
}
override open var shouldAutorotate: Bool {
return false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
// tableView.estimatedRowHeight = 200
// tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 200
tableView.estimatedSectionHeaderHeight = 75
tableView.sectionHeaderHeight = UITableViewAutomaticDimension
}
}
extension ViewController : UITableViewDataSource, UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView.tag == 0{
return 4
}
if collectionView.tag == 1{
return 4
}
if collectionView.tag == 2{
return 3
}
return 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "videoCell", for: indexPath) as! VideoCell
if collectionView.tag == 0{
cell.imageView.image = revitalImages[indexPath.row]
}
if collectionView.tag == 1{
cell.imageView.image = focusImages[indexPath.row]
}
cell.layer.borderWidth = 1
cell.layer.borderColor = UIColor(red:222/255, green:225/255, blue:227/255, alpha: 1).cgColor
return cell
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return categories.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! CategoryRow
cell.collectionView.delegate = self
cell.collectionView.dataSource = self
cell.collectionView.tag = indexPath.row
cell.collectionView.reloadData()
cell.titleLbl.text = categories[indexPath.row]
cell.contentView.backgroundColor = UIColor.white
cell.backgroundColor = UIColor.white
return cell
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView()
headerView.backgroundColor = UIColor.white
return headerView
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 400
}
func tableView(_ tableView: UITableView, willDisplayHeaderView view:UIView, forSection: Int) {
if let headerTitle = view as? UITableViewHeaderFooterView {
headerTitle.textLabel?.textColor = UIColor.clear
}
}
}
I want to show data dynamically without using tag 0,1,2,.....

UITableViewCell from Xib, cell hight and cell selection area

I have a UITableViewController, which has a custom cell that I want to display an image and labels. screenshots can explain my problem very well, it looks like this
.
And when I select any cell it looks like
In tableviewcontroller cell is not visible in proper shape according to constraints
here is my custom cell with autolayout constraints
How I can fix this issue? ... I created this tableviewcontroller programmatically without using storyboard.
here is code sample of data source and delegates of tableviewcontroller
override func numberOfSections(in tableView: UITableView) -> Int {
var numOfSections: Int = 0
let count = conversations.count
if count > 0 {
// tableView.separatorStyle = .none
numOfSections = 1
tableView.backgroundView = nil
}
else
{
let frame = CGRect(x: 0,
y: 0,
width: tableView.bounds.size.width,
height: tableView.bounds.size.height)
let noDataLabel: UILabel = UILabel(frame: frame)
noDataLabel.text = "You don't have any messages. 🙃"
noDataLabel.textColor = UIColor.black
noDataLabel.textAlignment = .center
tableView.backgroundView = noDataLabel
tableView.separatorStyle = .none
}
return numOfSections
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return conversations.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "inboxCell", for: indexPath) as! InboxCell
cell.conversation = conversations[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let uids = conversations[indexPath.row].conversationUseruids
for uid in uids{
if uid == Account.account.user.uid{
}
else{
User.getUser(with: uid, completion: { (user) in
self.selectedUser.append(user!)
})
}
}
tableView.deselectRow(at: indexPath, animated: true)
let index = indexPath.row as Int
messageVC.conversationIndex = index
messageVC.conversation = self.conversations[index]
navigationController?.pushViewController(messageVC, animated: true)
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 80
}
it happen because your image not have upper lower constraint if not working than let me know

Checkbox in Static Cell

 I am new to Swift and I am beginning to learn checkbox in table but my table working properly
I using static cell:
my Code:
var flagCell : Bool = false
override func viewDidLoad() {
super.viewDidLoad()
tableView.separatorInset = .zero
tableView.layoutMargins = .zero
let nav = self.navigationController?.navigationBar
nav?.tintColor = UIColor(red: 16.0, green: 18.0, blue: 34.0, alpha: 1.0)
nav?.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if flagCell == false{
cell.accessoryType = .checkmark
flagCell = true
}else {
cell.accessoryType = .none
flagCell = false
}
}
}
Mark put on through time.
How can it solve?
I also want to do UISwith si on, checkmarks appear at all Cell
How can I implement it ?
Put this code to cellForRowAtIndexPath
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellID")
if flagCell == false {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
}
And reload tableAfter taping
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
flagCell = !flagCell
tableView.reloadData()
}
Or you can use another method for cell updating:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
flagCell = !flagCell
tableView.reloadRows(at: [indexPath], with: .automatic)
}

UITableViewCell Selected Background Color on Multiple Selection

// 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?
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.
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
}
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
Swift 4.2
For multiple selections you need to set the UITableView property allowsMultipleSelection to true.
myTableView.allowsMultipleSelection = true
In case you subclassed the UITableViewCell, you override setSelected(_ selected: Bool, animated: Bool) method in your custom cell class.
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if selected {
contentView.backgroundColor = UIColor.green
} else {
contentView.backgroundColor = UIColor.blue
}
}
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
}
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:
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:
if let cell = self.table.cellForRowAtIndexPath(path) as? ICComplaintCategoryCell {
cell.reload()
}
Updated for Swift 3+, thanks #Bogy
You can also set cell's selectionStyle to.none in interface builder. The same solution as #AhmedLotfy provided, only from IB.
For Swift 3,4 and 5 you can do this in two ways.
1) class: UITableViewCell
override func awakeFromNib() {
super.awakeFromNib()
//Costumize cell
selectionStyle = .none
}
or
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
UITableViewCell has an attribute multipleSelectionBackgroundView.
https://developer.apple.com/documentation/uikit/uitableviewcell/1623226-selectedbackgroundview
Just create an UIView define the .backgroundColor of your choice and assign it to your cells .multipleSelectionBackgroundView attribute.
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
}
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).
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)
}
}
SWIFT 3/4
Solution for CustomCell.selectionStyle = .none if you set some else style you saw "mixed" background color with gray or blue.
And don't forget! func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) didn't call when 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
}
}
}
Swift 5 - This works for me:
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
}
You can use standard UITableViewDelegate methods
- (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;
}
in my situation this works, cause we need to select cell, change color, and when user taps 2 times on the selected cell further navigation should be performed.
Swift 4
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
let selectedCell = tableView.cellForRow(at: indexPath)! as! LeftMenuCell
selectedCell.contentView.backgroundColor = UIColor.blue
}
If you want to unselect the previous cell, also you can use the different logic for this
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
}
}

Resources