Change image on selection in UITableViewCell(swift 3 xcode) - ios

I have an imageView inside my tableViewCell and i would like to have its image changed on selection. This is the code I have for it:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let myCell = tableView.cellForRow(at: indexPath) as! TableCell
myCell.resourceIcons.image = UIImage(named: "RubiusResources2")
tableView.deselectRow(at: indexPath, animated: true)
}
The code works, but some of the other rows in a different section further down the tableView also seem change.
EDIT:
Using the comments bellow I came to the following solution:
I first created a 2D bool array to the amount of sections and rows my table had and set them all to false.
var resourceBool = Array(repeating: Array(repeating:false, count:4), count:12)
I then created an if statement to check if the array at indexPath was false or true. This would be where the states of the image would change.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let myCell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) as! TableCell
if (global.resourceBool[indexPath.section][indexPath.row] == false) {
myCell.resourceIcons.image = global.systemResourceImages[0]
} else if (global.resourceBool[indexPath.section][indexPath.row] == true) {
myCell.resourceIcons.image = global.systemResourceImages[1]
}
return myCell
}
Then, in the didSelectRow function I change the array at indexPath to true and reload the tableView data.
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
global.resourceBool[indexPath.section][indexPath.row] = true
tableView.reloadData()
tableView.deselectRow(at: indexPath, animated: true)
}
From my understanding, the states of an object must always be in the cellForRow.

One of the solution would be that you need to maintain a seperate list of rows you selected, compare them in cellForRowAt method.
Code would look something like this.
var selectedArray : [IndexPath] = [IndexPath]()
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let myCell = tableView.cellForRow(at: indexPath) as! TableCell
myCell.resourceIcons.image = UIImage(named: "RubiusResources2")
tableView.deselectRow(at: indexPath, animated: true)
if(!selectedArray.contains(indexPath))
{
selectedArray.append(indexPath)
}
else
{
// remove from array here if required
}
}
and then in cellForRowAt, write this code to set proper images
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
.
.
.
if(selectedArray.contains(indexPath))
{
// use selected image
}
else
{
// use normal image
}
.
.
.
}

Related

TableView CheckMark and Uncheck With Scroll Up Still Checked Cell Value In Ios Swift 4

TableView CheckMark Cell Value Removed After Scrolling Up It will Fix
TableView in You have face a problem many times to Checkmark after scroll Up then Scroll Down To show a Your Checkmark cell is will Removed Because cell is dequeueReusableCell So This Problem Fix , you Have just put Your code and Solved Your Problem.
Any More Help So Send Massage.
Thank you So much. :)
class ViewController: UIViewController , UITableViewDataSource , UITableViewDelegate{
var temp = [Int]()
var numarr = [Int]()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return numarr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "id")
cell = UITableViewCell.init(style: .default, reuseIdentifier: "id")
cell?.textLabel?.text = String(numarr[indexPath.row])
if temp.contains(numarr[indexPath.row] as Int)
{
cell?.accessoryType = .checkmark
}
else
{
cell?.accessoryType = .none
}
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
if temp.contains(numarr[indexPath.row] as Int)
{
cell?.accessoryType = .none
temp.remove(at: temp.index(of: numarr[indexPath.row])!)
}
else
{
cell?.accessoryType = .checkmark
temp.append(self.numarr[indexPath.row] as Int)
}
}
override func viewDidLoad() {
super.viewDidLoad()
for i in 1...100
{
numarr.append(i)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
I think if someone were to run your code it would not show any error. But with real data it probably will. The reason is the way you store your checkmarks. You store the data of a row into the temp array when you should be storing the actualy indexPath of the array so that only that row gets the checkmark. In your case, if a row has 1 inside it's label and you click on it, that cell will be highlighted. Now if you start scrolling and another cell contains 1 then that row will also be highlighted.
I have modified your example for the case of a single section. If there is more than one section, you need to store the indexPath instead of indexPath.row.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "id")
cell = UITableViewCell.init(style: .default, reuseIdentifier: "id")
cell?.textLabel?.text = String(numarr[indexPath.row])
if temp.contains(indexPath.row) {
cell?.accessoryType = .checkmark
} else {
cell?.accessoryType = .none
}
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
if temp.contains(indexPath.row) {
cell?.accessoryType = .none
temp.remove(at: indexPath.row)
} else {
cell?.accessoryType = .checkmark
temp.append(indexPath.row)
}
}
You are strongly discouraged from using a second array to keep the selected state.
This is Swift, an object oriented language. Use a custom struct for both num and the selected state.
In didSelectRowAt and didDeselectRowAt change the value of isSelected and reload the row.
And use always the dequeueReusableCell API which returns a non-optional cell.
struct Item {
let num : Int
var isSelected : Bool
}
var numarr = [Item]()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return numarr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "id", for: indexPath)
let item = numarr[indexPath.row]
cell.textLabel?.text = String(item)
cell.accessoryType = item.isSelected ? .checkmark : .none
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
updateSelection(at: indexPath, value : true)
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
updateSelection(at: indexPath, value : false)
}
func updateSelection(at indexPath: IndexPath, value : Bool) {
let item = numarr[indexPath.row]
item.isSelected = value
tableView.reloadRows(at: [indexPath], with: .none)
}
override func viewDidLoad() {
super.viewDidLoad()
(0...100).map{Item(num: $0, isSelected: false)}
}

Resize cell when click on custom button in Swift 4

I have a view controller in which i have used table view controller in it. In my cell there is a button on which when user click the cell size should come to 550 and when click again it should come back to its original height. I have tried bit code after searching for it but it isn't working is their any solution that can work for me?. My code is bit this,
var indexOfCellToExpand: Int!
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.row == indexOfCellToExpand {
return 170 + expandedLabel.frame.height - 38
}
return 170
}
Use Auto layout for Expand-collapse Cell,
Attaching Demo for that case
link:https://www.dropbox.com/s/ieltq0honml35l8/TAbleDemo.zip?dl=0.
set cell button height constraint and update constraint on Value on select- deselect event and just reload data
in main viewcontroller code
self.tblView.estimatedRowHeight = 100
self.tblView.rowHeight = UITableViewAutomaticDimension
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TblCell", for: indexPath) as! TblCell
cell.btnExpandCollepse.addTarget(self, action: #selector(ViewController.expandCollapse(sender:)), for: .touchUpInside)
return cell
}
#objc func expandCollapse(sender:UIButton) {
self.tblView.reloadData()
}
Code in Cell Class
#IBOutlet var btnExpandCollepse: UIButton!
#IBOutlet var constraintBtnHeight: NSLayoutConstraint!
#IBAction func onExpandCollepse(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
if !sender.isSelected{
self.constraintBtnHeight.constant = 50
}else{
self.constraintBtnHeight.constant = 500
}
}
for constraint check below image
http://prntscr.com/hur8ym
Updated Demo for custom Content height of Lable with Autoresizing Cell
https://www.dropbox.com/s/o742kflg5yeofb8/TAbleDemo%202.zip?dl=0
https://www.dropbox.com/s/o742kflg5yeofb8/TAbleDemo%202.zip?dl=0
Swift 4.x
fileprivate var expandedIndexSet = Set<IndexPath>()
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if expandedIndexSet.contains(indexPath) {
let cell = tableView.dequeueReusableCell(withIdentifier: "CELL_EXPANDED", for: indexPath) as! CellExpanded
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "CELL_COLLAPSED", for: indexPath) as! CellCollapsed
return cell
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
if expandedIndexSet.contains(indexPath) {
expandedIndexSet.remove(indexPath)
} else {
expandedIndexSet.insert(indexPath)
}
tableView.reloadRows(at: [indexPath], with: .fade)
}

CheckBox on tableview duplicating, Swift, iOS

I have a tableView that when selected changes an image from one to another. This all works fine but when I select a tableCell it changes the image, but when I scroll it has also changed the image of another cell that I didn't select.
Below is my code.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FeaturesCell") as! FeaturesCell
cell.featuresLabel.text = self.items[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
pickedFeatures.append(items[indexPath.row])
let cell = tableView.cellForRow(at: indexPath) as! FeaturesCell
cell.checkImage.image = #imageLiteral(resourceName: "tick-inside-circle")
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
pickedFeatures.remove(at: pickedFeatures.index(of: items[indexPath.row])!)
let cell = tableView.cellForRow(at: indexPath) as! FeaturesCell
cell.checkImage.image = #imageLiteral(resourceName: "No-tick-inside-circle")
}
If I use detqueureusable cell in the did select function then it just doesn't change the picture at all when selected.
You can use tableView.dequeueReusableCell(_), The problem is, you didn't maintain the status of the selected cells.
Example :
class viewController: UIVieWController, UITableViewDelegate, UITableViewDataSource {
var selectedCellList = [IndexPath]()
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FeaturesCell") as! FeaturesCell
cell.featuresLabel.text = self.items[indexPath.row]
if let _ = selectedCellList.index(of: indexPath) {
// Cell selected, update check box image with tick mark
cell.checkImage.image = #imageLiteral(resourceName: "tick-inside-circle")
} else {
// Cell note selected, update check box image without tick mark
cell.checkImage.image = #imageLiteral(resourceName: "No-tick-inside-circle")
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
pickedFeatures.append(items[indexPath.row])
if let index = selectedCellList.index(of: indexPath) {
selectedCellList.remove(at: index)
} else {
selectedCellList.append(indexPath)
}
tableView .reloadRows(at: [indexPath], with: .automatic)
}
}

Multiple checkmark in Tableview in swift3

How to do the multiple checkmark in tableview. I need to select the multiple checkmark in tableview and what are the checkmarks I need to select to place the multiple values in label.
Example player1,player2,player3 in label
here is my code
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return TypeOfAccountArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! UITableViewCell
let cell:TypeofAccountCell=tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TypeofAccountCell
cell.Uertype_lbl.text=TypeOfAccountArray[indexPath.row]
cell.selectionStyle = UITableViewCellSelectionStyle.none;
cell.Uertype_lbl.font = UIFont(name:"Roboto-Regular", size:13)
cell.Uertype_lbl.adjustsFontSizeToFitWidth = true
if (selectedIndex == indexPath as NSIndexPath?) {
cell.checkmarkbtn.setImage(UIImage(named: "checkmark.png"),for:UIControlState.normal)
} else {
cell.checkmarkbtn.setImage(UIImage(named: "uncheckmark.png"),for:UIControlState.normal)
}
// Configure the cell...
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath as IndexPath, animated: true)
let row = indexPath.row
print(TypeOfAccountArray[row])
selectedIndex = indexPath as NSIndexPath?
self.Type_of_account_txt.text = (TypeOfAccountArray[row])
self.Type_account_view.isHidden = true
tableView.reloadData()
}
Change your selectedindex to hold array of index path var selectedIndexes = [IndexPath](), on your cell xib, set your checkmark image on button selected stated and uncheckmark image on normal status and use the below code.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return TypeOfAccountArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:TypeofAccountCell=tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TypeofAccountCell
cell.Uertype_lbl.text=TypeOfAccountArray[indexPath.row]
cell.selectionStyle = UITableViewCellSelectionStyle.none;
cell.Uertype_lbl.font = UIFont(name:"Roboto-Regular", size:13)
cell.Uertype_lbl.adjustsFontSizeToFitWidth = true
// Configure the cell...
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath as IndexPath, animated: true)
let cell:TypeofAccountCell=tableView.cellForRow(at: indexPath) as! TypeofAccountCell
if selectedIndexes.contains(indexPath)
{
cell.checkmarkbtn.isSelected = false
if let index = selectedIndexes.index(of: indexPath) {
selectedIndexes.remove(at: index)
}
}
else
{
cell.checkmarkbtn.isSelected = true
selectedIndexes.append(indexPath)
}
}
self.Type_of_account_txt.text = ""
for element in selectedIndexes
{
self.Type_of_account_txt.text = (self.Type_of_account_txt.text ?? "") + "\(TypeOfAccountArray[element.row]) ,"
}
if (selectedIndexes.count > 0)
{
self.Type_of_account_txt.text = self.Type_of_account_txt.text?.substring(to: (self.Type_of_account_txt.text?.index(before: (self.Type_of_account_txt.text?.endIndex)!))!)
}
}
you need to follow this step :
In didSelectRowAt, you need to add and remove indexpath in array for multiple checkmark.
Now , in cellForRowAtIndexPath you need to check that current
indexPath consist in array .
if (![arrIndexPath containsObject: indexPath]) {
// do something
cell.checkmarkbtn.setImage(UIImage(named: "checkmark.png"),for:UIControlState.normal)
}

Expanding tableview cell data being overwritten when selected

I have a transaction tableview with different types of expenses that expands to show more detail when selected.
However the detail appears to be overwritten when this happens. I can see it flash and sometimes it does get populated. The textfields get populated correctly. I have been trying to debug this for a while, but not sure how to work around this problem.
Here is my current implementation:
// MARK: Tableview
extension TransactionViewController: UITableViewDelegate, UITableViewDataSource {
// MARK: - Table View
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CardCell", for: indexPath) as! CardTableViewCell
cell.delegate = self
var isDetailHidden = true
if indexPath.row == rowSelected {
isDetailHidden = false
}
let transaction = transactionList[indexPath.row]
cell.configureCell(transaction: transaction, isDetailHidden: isDetailHidden)
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return transactionList.count
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == rowSelected {
// don't refresh and set again.
return
}
rowSelected = indexPath.row
transactionBeingEdited = transactionList[indexPath.row]
transactionTableView.setContentOffset(CGPoint(x: 0, y: rowSelected! * 76), animated: true)
let cell = tableView.dequeueReusableCell(withIdentifier: "CardCell", for: indexPath) as! CardTableViewCell
cell.delegate = self
cell.configureDetailCell()
transactionTableView.reloadData()
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
let transaction = transactionList[indexPath.row]
coreDataManager.deleteTransaction(transaction: transaction)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.row != rowSelected {
return 76.5
} else {
return 323
}
}
The variables in the detail section are dropdown boxes using a library. I've configured it in the UITableViewCell class. Setting up the dropdown methods occurs in the awakefromnib method.
private func setupBillDropDown() {
billDropDown.anchorView = bill
billDropDown.bottomOffset = CGPoint(x: 0, y: bill.bounds.height)
billDropDown.dataSource = TransactionType.list
// Action triggered on selection
billDropDown.selectionAction = { [unowned self] (index, item) in
self.bill.setTitle(item, for: .normal)
self.bill.setTitleColor(UIColor.white, for: .normal)
// Update transaction
if let transactionBeingEdited = self.delegate?.transactionBeingEdited {
transactionBeingEdited.type = item
self.coreDataManager.saveToCoreData()
self.coreDataManager.nc.post(name: .transactionBeingEdited, object: nil, userInfo: nil)
}
}
}
Thanks in advance.
I think in func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) you are overwriting the configured cell by loading the table. Try this:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == rowSelected {
// don't refresh and set again.
return
}
rowSelected = indexPath.row
transactionBeingEdited = transactionList[indexPath.row]
transactionTableView.setContentOffset(CGPoint(x: 0, y: rowSelected! * 76), animated: true)
//let cell = tableView.dequeueReusableCell(withIdentifier: "CardCell", for: indexPath) as! CardTableViewCell
let cell = tableView.cellForRow(at: indexPath)
cell.configureDetailCell()
tableView.reloadRows(at: [indexPath], with: .none)
}
I figured out the issue after spending literally hours on it... It's because I was updating the buttons title using
bill.titleLabel!.text = transaction.type ?? "Select Bill"
insteaad of
bill.setTitle(transaction.type ?? "Select Bill", for: .normal)

Resources