Select ALL TableView Rows Programmatically Using selectRowAtIndexPath - ios

I'm trying to programmatically select all rows in my tableview using the following code:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:myTableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell") as! myTableViewCell
cell.accessoryType = .None
if allJobsSelected {
let bgColorView = UIView()
bgColorView.backgroundColor = UIColor(red: 250/255, green: 182/255, blue: 17/255, alpha: 1)
cell.contentView.backgroundColor = UIColor(red: 250/255, green: 182/255, blue: 17/255, alpha: 1)
cell.selectedBackgroundView = bgColorView
cell.accessoryType = .Checkmark
cell.highlighted = false
cell.selected = true
// cell.accessoryType = .Checkmark
self.tableView.selectRowAtIndexPath(indexPath, animated: true, scrollPosition: UITableViewScrollPosition.None)
self.tableView(self.tableView, didSelectRowAtIndexPath: indexPath)
}
var job: Jobs!
job = jobs[UInt(indexPath.row)] as! Jobs
cell.reports2JobTitle.text = job.jobTitle
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.tableView.allowsMultipleSelection = true
if let cell:myTableViewCell = tableView.cellForRowAtIndexPath(indexPath) as? myTableViewCell {
let bgColorView = UIView()
bgColorView.backgroundColor = UIColor(red: 250/255, green: 182/255, blue: 17/255, alpha: 1)
cell.contentView.backgroundColor = UIColor(red: 250/255, green: 182/255, blue: 17/255, alpha: 1)
cell.selectedBackgroundView = bgColorView
cell.accessoryType = .Checkmark
cell.highlighted = false
self.tableView.selectRowAtIndexPath(indexPath, animated: true, scrollPosition: UITableViewScrollPosition.Bottom)
}
}
My issue is that only the rows that have been dequeued are added to my table's data model when I segue to the next viewcontroller. In order to add all the rows to my table's data model I have to manually scroll through the whole table. How can I change this so all the selected rows are added to my table's data model without having to scroll through the whole table?
What I cannot understand is that after all my rows are selected I then loop through my indexPaths as follows but not all of the indexPaths are added unless I first scroll through the entire table.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier == "reportsDisplay") {
let controller = segue.destinationViewController as! ReportsDisplayViewController
var selectedJob : Jobs!
if let indexPaths = tableView.indexPathsForSelectedRows {
for i in 0 ..< indexPaths.count {
let thisPath = indexPaths[i]
selectedJob = jobs[UInt(thisPath.row)] as! Jobs
let jobTitle = selectedJob.jobTitle
let id = selectedJob.identifier
jobsToReport.append(jobTitle)
jobsID.append(id)
}
}
controller.reportedJobs = jobsToReport
controller.idOfJobs = jobsID
}
}

For Swift 3 and answering your question literally, regardless of your code.
func selectAllRows() {
for section in 0..<tableView.numberOfSections {
for row in 0..<tableView.numberOfRows(inSection: section) {
tableView.selectRow(at: IndexPath(row: row, section: section), animated: false, scrollPosition: .none)
}
}
}
If you want to inform the tableview delegate, use this method:
func selectAllRows() {
for section in 0..<tableView.numberOfSections {
for row in 0..<tableView.numberOfRows(inSection: section) {
let indexPath = IndexPath(row: row, section: section)
_ = tableView.delegate?.tableView?(tableView, willSelectRowAt: indexPath)
tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
tableView.delegate?.tableView?(tableView, didSelectRowAt: indexPath)
}
}
}

At the time allJobsSelected becomes true, you need to call the UITableView method selectRowAtIndexPath(_:animated:scrollPosition:) for each row of your table. In my case, I attached this functionality to the right bar button item which I named Select All. Calling this from cellForRowAtIndexPath is surely not the right place.
#IBAction func doSelectAll(sender: UIBarButtonItem) {
let totalRows = tableView.numberOfRowsInSection(0)
for row in 0..<totalRows {
tableView.selectRowAtIndexPath(NSIndexPath(forRow: row, inSection: 0), animated: false, scrollPosition: UITableViewScrollPosition.None)
}
}

Functional solution (Swift 5.1)
extension UITableViewDataSource where Self: UITableView {
/**
* Returns all IndexPath's in a table
* ## Examples:
* table.indexPaths.forEach {
* selectRow(at: $0, animated: true, scrollPosition: .none) // selects all cells
* }
*/
public var indexPaths: [IndexPath] {
return (0..<self.numberOfSections).indices.map { (sectionIndex: Int) -> [IndexPath] in
(0..<self.numberOfRows(inSection: sectionIndex)).indices.compactMap { (rowIndex: Int) -> IndexPath? in
IndexPath(row: rowIndex, section: sectionIndex)
}
}.flatMap { $0 }
}
}

Solution for Swift 5.5
This method can be logically made an extension of UITableView and must be called from the main thread:
extension UITableView {
// Must be called from the main thread
func selectAllRows() {
let totalRows = self.numberOfRows(inSection: 0)
for row in 0..<totalRows {
self.selectRow(at: IndexPath(row: row, section: 0), animated: true, scrollPosition: .none)
}
}
}
Note: this code is only for the only section

Related

Setting constraints to UITableView Footer Swft

I'm trying to place a footer with a UIButton, now I placed it only with frame and when I try it out across apple's iphones the button is not placed well due to the fact that I didn't set any auto-layout, the thing is Im trying to set auto-layout to the footer and it fails all the time also I'm not sure if its possible doing that, would love to get a handy help with that or even hints :).
Here's my code of the tableView:
import UIKit
import PanModal
protocol FilterTableViewDelegate {
func didUpdateSelectedDate(_ date: Date)
}
class FilterTableViewController: UITableViewController, PanModalPresentable {
var panScrollable: UIScrollView? {
return tableView
}
var albumsPickerIndexPath: IndexPath? // indexPath of the currently shown albums picker in tableview.
var delegate: FilterTableViewDelegate?
var datesCell = DatesCell()
override func viewDidLoad() {
super.viewDidLoad()
setupTableView()
// registerTableViewCells()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// tableView.frame = view.bounds
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
// MARK: - View Configurations
func setupTableView() {
tableView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true
tableView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
tableView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
tableView.separatorStyle = .singleLine
tableView.isScrollEnabled = false
tableView.allowsSelection = true
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 600
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
}
func indexPathToInsertDatePicker(indexPath: IndexPath) -> IndexPath {
if let albumsPickerIndexPath = albumsPickerIndexPath, albumsPickerIndexPath.row < indexPath.row {
return indexPath
} else {
return IndexPath(row: indexPath.row + 1, section: indexPath.section)
}
}
// MARK: - UITableViewDataSource
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// If datePicker is already present, we add one extra cell for that
if albumsPickerIndexPath != nil {
return 5 + 1
} else {
return 5
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.row {
case 0:
let byActivityCell = UINib(nibName: "byActivityCell",bundle: nil)
self.tableView.register(byActivityCell,forCellReuseIdentifier: "byActivityCell")
let activityCell = tableView.dequeueReusableCell(withIdentifier: "byActivityCell", for: indexPath) as! byActivityCell
activityCell.selectionStyle = .none
return activityCell
case 1:
let byTypeCell = UINib(nibName: "ByType",bundle: nil)
self.tableView.register(byTypeCell,forCellReuseIdentifier: "byTypeCell")
let typeCell = tableView.dequeueReusableCell(withIdentifier: "byTypeCell", for: indexPath) as! ByType
typeCell.selectionStyle = .none
return typeCell
case 2:
let byHashtagsCell = UINib(nibName: "ByHashtags",bundle: nil)
self.tableView.register(byHashtagsCell,forCellReuseIdentifier: "byHashtagsCell")
let hashtagsCell = tableView.dequeueReusableCell(withIdentifier: "byHashtagsCell", for: indexPath) as! ByHashtags
hashtagsCell.selectionStyle = .none
return hashtagsCell
case 3:
let byDatesCell = UINib(nibName: "DatesCell",bundle: nil)
self.tableView.register(byDatesCell,forCellReuseIdentifier: "byDatesCell")
let datesCell = tableView.dequeueReusableCell(withIdentifier: "byDatesCell", for: indexPath) as! DatesCell
datesCell.selectionStyle = .none
datesCell.datesTableViewCellDelegate = self
return datesCell
case 4:
let byAlbumCell = UINib(nibName: "AlbumCell",bundle: nil)
self.tableView.register(byAlbumCell,forCellReuseIdentifier: "byAlbumCell")
let albumCell = tableView.dequeueReusableCell(withIdentifier: "byAlbumCell", for: indexPath) as! AlbumCell
albumCell.configureCell(choosenAlbum: "Any")
albumCell.selectionStyle = .none
return albumCell
case 5:
let albumPickerCell = UINib(nibName: "AlbumsPickerTableViewCell", bundle: nil)
self.tableView.register(albumPickerCell, forCellReuseIdentifier: "albumPickerCell")
let albumsPicker = tableView.dequeueReusableCell(withIdentifier: "albumPickerCell", for: indexPath) as! AlbumsPickerTableViewCell
return albumsPicker
default:
return UITableViewCell()
}
}
// MARK: - footer Methods:
override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
return getfooterView()
}
func getfooterView() -> UIView
{
let footerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 400))
let applyFiltersBtn = UIButton(frame: CGRect(x: 0, y: 0, width: 380, height: 40))
applyFiltersBtn.center = footerView.center
applyFiltersBtn.layer.cornerRadius = 12
applyFiltersBtn.layer.masksToBounds = true
applyFiltersBtn.setTitle("Apply Filters", for: .normal)
applyFiltersBtn.backgroundColor = #colorLiteral(red: 0.1957295239, green: 0.6059523225, blue: 0.960457623, alpha: 1)
// doneButton.addTarget(self, action: #selector(hello(sender:)), for: .touchUpInside)
footerView.addSubview(applyFiltersBtn)
return footerView
}
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 10
}
// MARK: TableViewDelegate Methods:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
tableView.beginUpdates()
// 1 - We Delete the UIPicker when the user "Deselect" thr row.
if let datePickerIndexPath = albumsPickerIndexPath, datePickerIndexPath.row - 1 == indexPath.row {
tableView.deleteRows(at: [datePickerIndexPath], with: .fade)
self.albumsPickerIndexPath = nil
} else {
// 2
// if let datePickerIndexPath = albumsPickerIndexPath {
// tableView.deleteRows(at: [datePickerIndexPath], with: .fade)
// }
albumsPickerIndexPath = indexPathToInsertDatePicker(indexPath: indexPath)
tableView.insertRows(at: [albumsPickerIndexPath!], with: .fade)
tableView.deselectRow(at: indexPath, animated: true)
}
tableView.endUpdates()
}
override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
if indexPath.row == 4 {
return indexPath
} else {
return nil
}
}
}
extension FilterTableViewController: DatesTableViewCellDelegate {
func didButtonFromPressed() {
print("Button From is Pressed")
let pickerController = CalendarPickerViewController(
baseDate: Date(),
selectedDateChanged: { [weak self] date in
guard let self = self else { return }
// self.item.date = date
//TODO: Pass the date to the DatesCell to update the UIButtons.
self.delegate?.didUpdateSelectedDate(date)
self.tableView.reloadRows(at: [IndexPath(row: 3, section: 0)], with: .fade)
})
present(pickerController, animated: true, completion: nil)
}
func didButtonToPressed() {
//TODO: Present our custom calendar
let calendarController = CalendarPickerViewController(
baseDate: Date(),
selectedDateChanged: { [weak self] date in
guard let self = self else { return }
self.tableView.reloadRows(at: [IndexPath(row: 3, section: 0)], with: .fade)
})
self.present(calendarController, animated: true, completion: nil)
}
}
First, a tip (based on this and other questions you've posted): Simplify what you're doing. When you post code referencing 5 different cell classes along with code for handling cell action delegates, inserting and deleting, etc... but your question is about Section Footer layout, it gets difficult to help.
So, here's an example of a simple table view controller, using a default cell class, and a custom UITableViewHeaderFooterView for the section footer:
class MySectionFooterView: UITableViewHeaderFooterView {
let applyFiltersBtn = UIButton()
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
configureContents()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
configureContents()
}
func configureContents() {
applyFiltersBtn.translatesAutoresizingMaskIntoConstraints = false
applyFiltersBtn.layer.cornerRadius = 12
applyFiltersBtn.layer.masksToBounds = true
applyFiltersBtn.setTitle("Apply Filters", for: .normal)
applyFiltersBtn.backgroundColor = #colorLiteral(red: 0.1957295239, green: 0.6059523225, blue: 0.960457623, alpha: 1)
contentView.addSubview(applyFiltersBtn)
let g = contentView.layoutMarginsGuide
NSLayoutConstraint.activate([
// use layoutMarginsGuide for top and bottom
applyFiltersBtn.topAnchor.constraint(equalTo: g.topAnchor, constant: 0.0),
applyFiltersBtn.bottomAnchor.constraint(equalTo: g.bottomAnchor, constant: 0.0),
// inset button 20-pts from layoutMarginsGuide on each side
applyFiltersBtn.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
applyFiltersBtn.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0),
// make button height 40-pts
applyFiltersBtn.heightAnchor.constraint(equalToConstant: 40.0),
])
}
}
class SectionFooterViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// register cell class for reuse
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
// register Section Footer class for reuse
tableView.register(MySectionFooterView.self, forHeaderFooterViewReuseIdentifier: "mySectionFooter")
tableView.sectionFooterHeight = UITableView.automaticDimension
tableView.estimatedSectionFooterHeight = 50
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 8
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = "\(indexPath)"
return cell
}
override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let view = tableView.dequeueReusableHeaderFooterView(withIdentifier:"mySectionFooter") as! MySectionFooterView
return view
}
}
To handle tapping the button in the section footer, you can either assign it an action in viewForFooterInSection, or build that action into the MySectionFooterView class and use a closure or protocol / delegate pattern.

Swiping on a tableview is deselecting all selected rows trailingSwipeActionsConfigurationForRowAt

Recently implemented trailingSwipeActionsConfigurationForRowAt , where after swiping from right to left showing two options and its working fine. But the problem is when i select multiple rows or single row, after swiping the row/s they are getting deselected. Is there a way to keep the selection even after swiping?
Below is my code
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let renameAction = contextualToggleRenameAction(forRowAtIndexPath: indexPath)
let lastResAction = contextualToggleLastResponseAction(forRowAtIndexPath: indexPath)
let swipeConfig = UISwipeActionsConfiguration(actions: [renameAction, lastResAction])
swipeConfig.performsFirstActionWithFullSwipe = false
return swipeConfig
}
func contextualToggleLastResponseAction(forRowAtIndexPath indexPath: IndexPath) -> UIContextualAction {
let sensorData = sensorsList?[indexPath.row]
var lastResponse = ""
if sensorData != nil{
if let lstRes = sensorData!["last_response"] as? String{
lastResponse = lstRes
}
}
let action = UIContextualAction(style: .normal, title: lastResponse) { (contextAction: UIContextualAction, sourceView: UIView, completionHandler: (Bool) -> Void) in
print("Last Response Action")
}
action.backgroundColor = UIColor(red: 61/255, green: 108/255, blue: 169/255, alpha: 1.0)
return action
}
Holy crap, I fixed this stupid issue.
Yes, yes make sure tableView.allowsSelectionDuringEditing = true and tableView.allowsMultipleSelectionDuringEditing = true.
But...
Shout-out to this SO answer which almost directly led me on the way to success (see here).
KEY: Re-select/de-select the rows in your implementation of setEditing, which is a method you override. UITableView goes into editing mode when swiping.
IMPORTANT NOTE: Call super.setEditing(...) before any of your code, as shown below, or it likely won't work, or at least not perfectly.
override func setEditing(_ editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
for i in 0..<your data.count {
if this item is selected {
self.tableView.selectRow(at: IndexPath(row: i, section: 0), animated: false, scrollPosition: .none)
} else {
self.tableView.deselectRow(at: IndexPath(row: i, section: 0), animated: false)
}
}
}
A swipe is considered as an edit, so you can enable allowsSelectionDuringEditing if you want to keep the selected state:
tableView.allowsSelectionDuringEditing = true
Depending on indexPathsForSelectedRows doesn't always give the expected result.
Instead you should maintain and array of selectedIndexPaths.
Here is a code snippet to demonstrate:
var selectedIndexPaths = [IndexPath]()
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if selectedIndexPaths.contains(indexPath) {
selectedIndexPaths.removeAll { (ip) -> Bool in
return ip == indexPath
}else{
selectedIndexPaths.append(indexPath)
}
}
You can simply do this :
Create array in your controller for selected index
var arrSelectedIndex : [Int] = []
In didSelect,
if arrSelectedIndex.contains(indexPath.row) { // Check index is selected or not
// If index selected, remove index from array
let aIndex = arrSelectedIndex.firstIndex(of: indexPath.row)
arrSelectedIndex.remove(at: aIndex!)
}
else {
// If index not selected, add index to array
arrSelectedIndex.append(indexPath.row)
}
// reload selected row, or reloadData()
self.tblView.reloadRows([indexPath.row], with: .automatic)
Edit
In trailingSwipeActionsConfigurationForRowAt,
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?
{
if self.arrSelectedIndex.contains(indexPath.row) {
let action = UIContextualAction(style: .normal, title: "") { (action, view, handler) in
}
action.backgroundColor = .green
let configuration = UISwipeActionsConfiguration(actions: [])
configuration.performsFirstActionWithFullSwipe = false
return configuration
}
let action = UIContextualAction(style: .normal, title: "Selected") { (action, view, handler) in
}
action.backgroundColor = .green
let configuration = UISwipeActionsConfiguration(actions: [action])
configuration.performsFirstActionWithFullSwipe = false
return configuration
}
Output

How to fix UITableView cell repeat in swift 4

When I create a new cell it will automatically mark
or when I marked the first one, I was creating multiple
Cell, there will be duplicates marked
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let itemCellIdentifier = "itemCell"
guard let itemCell = itemCardTableView.dequeueReusableCell(withIdentifier: itemCellIdentifier, for: indexPath) as? ItemCardTableViewCell else {
return UITableViewCell()
}
let itemCard = dataManager.items[indexPath.row]
itemCell.itemTitle.text = itemCard.title
if itemCard.isFinish {
itemCell.itemCellView.backgroundColor = UIColor(red: 0, green: 123, blue: 0)
}
return itemCell
}
Add cell method
let confirm = UIAlertAction(title: "確認", style: .default) { (action: UIAlertAction) in
guard let title = addAlert.textFields?.first?.text else { return }
let newItem = ItemCard(title: title, isFinish: false)
self.dataManager.items.append(newItem)
let indexPath = IndexPath(row: self.itemCardTableView.numberOfRows(inSection: 0), section: 0)
self.itemCardTableView.insertRows(at: [indexPath], with: .left)
When I create new data isFinish = false
How can I fix data duplication?
You should provide else case to set default background color.
if itemCard.isFinish {
itemCell.itemCellView.backgroundColor = UIColor(red: 0, green: 123, blue: 0)
} else {
itemCell.itemCellView.backgroundColor = UIColor.white
}
If I understood your question right, You should hold the isFinish flag somewhere out of the cell, because it's being reused by tableView.
You can create the finished = [Bool]() is your UIViewController and every time check finished[indexPath.row] to see if it's marked or not and pass the boolean to your cell.

How to reload the collection view data in table view cell after clicking another table view cell's collection view data in swift 3?

Here I am loading collection view data dynamically in table view cell and table view cells also created on dynamic json array count and here after selecting any element in collection view which is in first table view cell then the collection view needs to be reloaded with new data which is in second table view cell can anyone help me how to reload the collection view in second table view cell swift 3 if this is not possible can anyone provide me any alternative layout to implement this ?
Here is my cell for row method
if indexPath.section == 0 {
let cell = addToCartTableView.dequeueReusableCell(withIdentifier: "addToCartCollectionCell") as! AddToCartCollectionTableViewCell
cell.configurableProduct = self.detailModel
print(self.detailModel)
cell.collectionView.tag = indexPath.row
self.addToCartTableView.setNeedsLayout()
self.addToCartTableView.layoutIfNeeded()
cell.collectionView.reloadData()
cell.cellLabel.text = detailModel?.extensionAttribute?.productOptions[indexPath.row].label
if detailModel?.extensionAttribute?.productOptions[indexPath.row].label == "Size"{
cell.sizeGuideBtn.isHidden = false
}else{
cell.sizeGuideBtn.isHidden = true
}
cell.getCurrentRow = indexPath.row
return cell
}else {
let cell = addToCartTableView.dequeueReusableCell(withIdentifier: "addToCartQtyCell") as! AddToCartQuantityTableViewCell
self.addToCartTableView.setNeedsLayout()
self.addToCartTableView.layoutIfNeeded()
cell.QtyLabel.text = "Qty"
return cell
}
Here is my table view cell code
override func awakeFromNib() {
super.awakeFromNib()
collectionView.delegate = self
collectionView.dataSource = self
print(getCurrentRow)
// Initialization code
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 50, height: 30)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
print(configurableProduct?.extensionAttribute?.productOptions[getCurrentRow].values.count)
return (configurableProduct?.extensionAttribute?.productOptions[getCurrentRow].values.count)!
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! AddToCartCollectionViewCell
if indexPath.item == 0 {
let items = configurableProduct?.extensionAttribute?.productOptions[getCurrentRow].values[indexPath.row]
cell.collectionLabel.text = "\(items?.valueIndex as! Int)"
if indexPath.item == self.selectedIndex{
cell.backgroundColor = #colorLiteral(red: 0.007509540026, green: 0.6581087804, blue: 0.01165772038, alpha: 1)
}else if self.selectedIndex == nil {
cell.backgroundColor = UIColor.white
}else{
cell.backgroundColor = UIColor.white
}
}
else {
if selectedValue != nil {
for item in (self.configurableProduct?.extensionAttribute?.productStock)! {
// let jsonStr = "{\"label\":\"57-175\",\"stock\":0}"
let dict = try! JSONSerialization.jsonObject(with: item.data(using: .utf8)!, options: []) as! [String:Any]
let labelValue = dict["label"] as! String
print(labelValue)
let values:[String] = labelValue.components(separatedBy: "-")
print(values)
self.colorNumber = Int(values[0])
self.sizeNumber = Int(values[1])
let stock = dict["stock"] as! Int
let value = selectedValue
if value == self.colorNumber {
if stock != 0 {
self.sizeArray.append(self.sizeNumber!)
print(self.sizeArray)
cell.collectionLabel.text = "\(self.sizeNumber)"
}
}
}
if indexPath.item == self.selectedIndex{
cell.backgroundColor = #colorLiteral(red: 0.007509540026, green: 0.6581087804, blue: 0.01165772038, alpha: 1)
}else if self.selectedIndex == nil {
cell.backgroundColor = UIColor.white
}else{
cell.backgroundColor = UIColor.white
}
}
else {
let items = configurableProduct?.extensionAttribute?.productOptions[getCurrentRow].values[indexPath.item]
print(items?.valueIndex)
for item in (self.configurableProduct?.extensionAttribute?.productStock)! {
// let jsonStr = "{\"label\":\"57-175\",\"stock\":0}"
let dict = try! JSONSerialization.jsonObject(with: item.data(using: .utf8)!, options: []) as! [String:Any]
let labelValue = dict["label"] as! String
print(labelValue)
let values:[String] = labelValue.components(separatedBy: "-")
print(values)
self.colorNumber = Int(values[0])
self.sizeNumber = Int(values[1])
let stock = dict["stock"] as! Int
let value = self.selectedIndex
if value == self.colorNumber {
if stock != 0 {
self.sizeArray.append(self.sizeNumber!)
print(self.sizeArray)
cell.collectionLabel.text = "\(items?.valueIndex as! Int)"
}
}else {
cell.collectionLabel.text = "\(items?.valueIndex as! Int)"
}
}
if indexPath.item == self.selectedIndex{
cell.backgroundColor = #colorLiteral(red: 0.007509540026, green: 0.6581087804, blue: 0.01165772038, alpha: 1)
}else if self.selectedIndex == nil {
cell.backgroundColor = UIColor.white
}else{
cell.backgroundColor = UIColor.white
}
}
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if collectionView.tag == 0 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! AddToCartCollectionViewCell
cell.backgroundColor = #colorLiteral(red: 0.007509540026, green: 0.6581087804, blue: 0.01165772038, alpha: 1)
cell.collectionLabel.layer.cornerRadius = 15
cell.collectionLabel.layer.borderColor = #colorLiteral(red: 0.007509540026, green: 0.6581087804, blue: 0.01165772038, alpha: 1)
self.dataSelected = true
self.selectedIndex = indexPath.item
print(self.selectedIndex)
self.collectionView.reloadData()
self.sizeArray.removeAll()
self.selectedValue = configurableProduct?.extensionAttribute?.productOptions[1].values[indexPath.item].valueIndex
self.getCurrentRow = 1
self.collectionView.reloadData()
print(self.selectedValue)
}
else {
print(collectionView.tag)
}
}
here is my layout image
in didSelectItemAt of collection view, reload the table cell which contains size by doing
let indexpath = IndexPath(item: value, section: 0)
tableview.reloadRows(at: [indexpath], with: .none)
here value is position of row which you want to upate
Create a new variable "cellObj" which data type is same as you custom cell where you added collection view.
var cellObj:AddToCartCollectionTableViewCell!
After add assign cellObj value after this line.
let cell = addToCartTableView.dequeueReusableCell(withIdentifier: "addToCartCollectionCell") as! AddToCartCollectionTableViewCell
cellObj = cell
*** After doing you are able to reload collection view any where.
cellObj.collectionView.reloadData()
DispatchQueue.main.async {
// cell!.tableView.reloadData()
collectionView.reloadItems(at: [indexPath])
cell!.tableView.reloadData()
}
})

Function does not work correctly until after a row has been selected

I have a tableview inside a viewcontroller. I have a little function to select all rows in the tableview. When I first display the viewcontroller and hit the select all button the function does not work. However, if I firstly select a row and then press the select all button, the function works as it should and all rows are selected. I'm not sure why this is happening. The tableview's delegate and data source have been set up in the storyboard.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:myTableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell") as! myTableViewCell
cell.accessoryType = .None
if allJobsSelected {
let bgColorView = UIView()
bgColorView.backgroundColor = UIColor(red: 250/255, green: 182/255, blue: 17/255, alpha: 1)
cell.contentView.backgroundColor = UIColor(red: 250/255, green: 182/255, blue: 17/255, alpha: 1)
cell.selectedBackgroundView = bgColorView
cell.accessoryType = .Checkmark
cell.highlighted = false
cell.selected = true
// cell.accessoryType = .Checkmark
self.tableView.selectRowAtIndexPath(indexPath, animated: true, scrollPosition: UITableViewScrollPosition.None)
self.tableView(self.tableView, didSelectRowAtIndexPath: indexPath)
}
var job: Jobs!
job = jobs[UInt(indexPath.row)] as! Jobs
cell.reports2JobTitle.text = job.jobTitle
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.tableView.allowsMultipleSelection = true
if let cell:myTableViewCell = tableView.cellForRowAtIndexPath(indexPath) as? myTableViewCell {
let bgColorView = UIView()
bgColorView.backgroundColor = UIColor(red: 250/255, green: 182/255, blue: 17/255, alpha: 1)
cell.contentView.backgroundColor = UIColor(red: 250/255, green: 182/255, blue: 17/255, alpha: 1)
cell.selectedBackgroundView = bgColorView
cell.accessoryType = .Checkmark
cell.highlighted = false
self.tableView.selectRowAtIndexPath(indexPath, animated: true, scrollPosition: UITableViewScrollPosition.Bottom)
}
}
#IBAction func doSelectAll(sender: UIBarButtonItem) {
let totalRows = tableView.numberOfRowsInSection(0)
for row in 0..<totalRows {
tableView.selectRowAtIndexPath(NSIndexPath(forRow: row, inSection: 0), animated: false, scrollPosition: UITableViewScrollPosition.None)
}
}
It would probably be a good idea to move this line:
self.tableView.allowsMultipleSelection = true
to your viewDidLoad
You are not guaranteed that the didSelect is called immediately -- it might be that each select is turning off the previous one and then a single didSelect is being called on the last row.

Resources