Select multiple rows in tableview and tick the selected ones - swift

I'm loading a tableView from a plist file. This works with no problems. I just simply want to "tick" the selected rows. At the moment, with my code it didn't work as desired. At the moment, it looks as below:
tap row1 (it will tick row 1 = good)
tap row1 again (nothing happens = bad. I expect here the row to be unticked)
While tapping again on row 1, it unticks then. After the second tap on it.
when I tap row0 at the initial load of the tableview it never ticks me the row
my code:
class portals: UITableViewController {
var lastSelectedIndexPath = NSIndexPath(forRow: -1, inSection: 0)
...
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as! UITableViewCell
// Configure the cell...
cell.textLabel!.text = portals[indexPath.row]
return cell
}
// Check which portal is selected
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var whichPortalIsSelected: String = ""
// Get Cell Label
let indexPath = tableView.indexPathForSelectedRow();
// Tick the selected row
if indexPath!.row != lastSelectedIndexPath?.row {
let newCell = tableView.cellForRowAtIndexPath(indexPath!)
newCell?.accessoryType = .Checkmark
lastSelectedIndexPath = indexPath
whichPortalIsSelected = newCell!.textLabel!.text!
println("You selected cell #\(lastSelectedIndexPath.row)!") //PPP
println("You selected portal #\(whichPortalIsSelected)!") //PPP
// Un-Tick unselected row
} else {
let newCell = tableView.cellForRowAtIndexPath(indexPath!)
newCell?.accessoryType = .None
whichPortalIsSelected = newCell!.textLabel!.text!
println("You unselected cell #\(indexPath!.row)!") //PPP
println("You unselected portal #\(whichPortalIsSelected)!") //PPP
}
}
}

Swift 4
First, make your tableView support multiple selection :
self.tableView.allowsMultipleSelection = true
self.tableView.allowsMultipleSelectionDuringEditing = true
Then simply subclass UITableViewCell like this :
class CheckableTableViewCell: UITableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.selectionStyle = .none
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
self.accessoryType = selected ? .checkmark : .none
}
}
Finally, use it in your cellForRowAt indexPath as such :
let cell = tableView.dequeueReusableCell(withIdentifier: "cell",
for: indexPath) as? CheckableTableViewCell
If you have to, don't forget to subclass your prototype cell in your xib/storyboard :

First of all, go to your Storyboard and select you tableview and in the Attributes Inspector, set Selection to Multiple Selection.
Attributes Inspector with multiple selection
Then, override the setSelected(_ selected: Bool, animated: Bool) function in the subclass of UITableViewCell.
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
accessoryType = selected ? UITableViewCellAccessoryType.checkmark : UITableViewCellAccessoryType.none
}

This enable untick.
class TableViewController: UITableViewController
{
var lastSelectedIndexPath = NSIndexPath(forRow: -1, inSection: 0)
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath)
// Configure the cell...
cell.textLabel!.text = "row: \(indexPath.row)"
if cell.selected
{
cell.selected = false
if cell.accessoryType == UITableViewCellAccessoryType.None
{
cell.accessoryType = UITableViewCellAccessoryType.Checkmark
}
else
{
cell.accessoryType = UITableViewCellAccessoryType.None
}
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
let cell = tableView.cellForRowAtIndexPath(indexPath)
if cell!.selected
{
cell!.selected = false
if cell!.accessoryType == UITableViewCellAccessoryType.None
{
cell!.accessoryType = UITableViewCellAccessoryType.Checkmark
}
else
{
cell!.accessoryType = UITableViewCellAccessoryType.None
}
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return 100
}
}

you have to make a costume class to get the selected state of the cell where you must override a func called
setSelected(_ selected: Bool, animated: Bool)
or the tick will be displayed randomly as you scroll ...
here is an example of what i did:
1- created a class for the cell
2- added an outlet for an image to display the tick (you can escape this if you don't want a costume tick image)
3- overrided the function and used the param selected :D
here is my class:
import UIKit
class AddLocationCell: UITableViewCell {
#IBOutlet weak var check: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if selected{
check.image = UIImage(named:"check_active")
}else{
check.image = UIImage(named:"check_normal")
}
// Configure the view for the selected state
}
}

There are many solutions to this problem, here's one I came up with. I am using the built in cell "selected" property so the tableview saves it for us. Just make sure in your storyboard or when you setup the tableview in code you use multiple selection.
import UIKit
class TableViewController: UITableViewController
{
var lastSelectedIndexPath = NSIndexPath(forRow: -1, inSection: 0)
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as! UITableViewCell
// Configure the cell...
cell.textLabel!.text = "row: \(indexPath.row)"
if cell.selected
{
cell.accessoryType = UITableViewCellAccessoryType.Checkmark
}
else
{
cell.accessoryType = UITableViewCellAccessoryType.None
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
let cell = tableView.cellForRowAtIndexPath(indexPath)
if cell!.selected == true
{
cell!.accessoryType = UITableViewCellAccessoryType.Checkmark
}
else
{
cell!.accessoryType = UITableViewCellAccessoryType.None
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return 100
}
}
I made a sample project here: https://github.com/brcimo/SwiftTableViewMultipleSelection

Related

How to save checkmark after using search in SearchBar?

I am trying to make a search bar in iOS and have made it to where it filters results and then when you click on it, it shows a checkmark. When I delete the search text, the check mark goes away and the full page of cells appears but the cell that I selected in the search is not selected with a check mark. This is implemented in my cell by setSelected method:
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if selected {
accessoryType = .checkmark
} else {
accessoryType = .none
}
}
I haven't any logic with checkmark in cellForRowAt and didSelectRowAt methods.
Here is a GIF of my problem
Can someone help me?
I assume all you're currently doing is setting the checkmark on your cell. The cell will be reused and you'll lose the checkmark.
What you need to do is to keep track of the items, e.g. in a Set, that the user has checked so far. Upon rendering items in the table view, you'll need to consult this set whether the item is checked. If it is, you'll want to add the checkmark to the cell.
Something along these lines where Item is your cell model. This should get you started. You should be able to extend this to a data set with groups for table headers.
/// The items that have been checked.
var checkedItems = Set<Item>()
/// All items that are shown when no search has been performed.
var allItems: [Item]
/// The currently displayed items, which is the same as `allItems` in case no
/// search has been performed or a subset of `allItems` in case a search is
/// currently active.
var displayedItems: [Item]
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let item = displayedItems[indexPath.row]
let cell = // Construct your cell as usual.
if checkedItems.contains(item) {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let item = displayedItems[indexPath.row]
if checkedItems.contains(item) {
checkedItems.remove(item)
cell.accessoryType = .none
} else {
checkedItems.insert(item)
cell.accessoryType = .checkmark
}
}
func updateSearchResults(for searchController: UISearchController) {
displayedItems = // Set the displayed items based on the search text.
tableView.scrollRectToVisible(.zero, animated: false)
tableView.reloadData()
}
I solved my problem in this way:
var selectedCellIndex: String?
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let key = sectionTitles[indexPath.section]
if let values = dictionary[key] {
selectedCellIndex = values[indexPath.row]
}
tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
let generator = UIImpactFeedbackGenerator(style: .light)
generator.impactOccurred()
}
public func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
tableView.cellForRow(at: indexPath)?.accessoryType = .none
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.tintColor = Color.main()
cell.selectionStyle = .none
let key = sectionTitles[indexPath.section]
if let values = dictionary[key] {
cell.textLabel?.text = values[indexPath.row]
if values[indexPath.row] == selectedCellIndex {
cell.accessoryType = .checkmark
}
}
return cell
}

How do I inject or add data to my table as it isn't working?

I just cannot seem to update data in Swift! I am trying to build a radio player app for a friends radio station so when a song changes I need to update the playlist viewcontroller.
The data from my Main View Controler is a instance of a struct. I know there is data being generated and it is passed to the table but for whatever reason the array isn't updating. I am sure it is something simple.
I have tried directly injecting the data with a call, using a protocol and using a function. Using the protocol and function I can see the passed data via print statement.
class PlaylistVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
//Mark: Variables ~~~~~~~~~~~~###########################################
var sourceDatas = [PlaylistData]()
//Mark: View Containers ~~~~~############################################
private let bg = GradientBG()
private let closeButton = UIButton()
let playlistTable = UITableView()
//Mark: Overrides ~~~~~~~~~~~~###########################################
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
playlistTable.delegate = self
playlistTable.dataSource = self
layoutUI()
setupTable()
setupClose()
}
//Mark: objc func's ~~~~~~~~~~~###########################################
#IBAction func handleXButton() {
dismiss(animated: true, completion: nil)
}
func handleMoreInfo(_ playlist: PlaylistData) {
let vc = SongPopUp()
vc.buildLables(playlist)
vc.modalPresentationStyle = .overCurrentContext
self.present(vc, animated: true, completion: nil )
}
//##################################################################
//Mark: Pass Data ##################################################
//Mark: Not Working!! ##############################################
//##################################################################
func handlePlaylist(_ with: PlaylistData) {
print(with)
sourceDatas.append(with)
//sourceDatas.insert(with, at: 0)
playlistTable.reloadData()
}
//Mark: Table view ################################################
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sourceDatas.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:UITableViewCell = UITableViewCell(style: .subtitle, reuseIdentifier: "myCell")
cell.backgroundColor = .clear
cell.selectionStyle = .none
tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath)
if let text = cell.textLabel {
components.layoutHeadingLable(sender: text, title: sourceDatas[indexPath.row].heading, size: 20)
}
if let dtext = cell.detailTextLabel {
components.layoutSubheadingLable(sender: dtext, title: sourceDatas[indexPath.row].subheading, size: 14)
}
if sourceDatas[indexPath.item].hasStoreLink {
cell.accessoryType = .detailButton
cell.tintColor = .white
}
return cell
}
func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
let dataToPass = self.sourceDatas[indexPath.row]
print("Extended~~~~~~~~~~~~~~~~~~~~")
print(dataToPass)
handleMoreInfo(sourceDatas[indexPath.row])
}
//Mark: Setup Table ~~~~~~~~~~~~~~###########################################
func setupTable() {
playlistTable.backgroundColor = .clear
playlistTable.separatorStyle = .singleLine
playlistTable.rowHeight = 45
playlistTable.register(UITableViewCell.self, forCellReuseIdentifier: "myCell")
}
......
I think it's something wrong with your cellForRowAt
Try to make it simple first, like:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath) as! UITableViewCell
cell.textLabel?.text = sourceDatas[indexPath.row]
return cell
}
See whether you can find the added object. Then dive into the detail settings of your cell.

Removing all Sublayers from UitableViewCell

I have UITableView with 2 expanded Sections.
So, when I click on section's header, rows will be hidden:
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
print("Section: \(indexPath.section), Row \(indexPath.row), \(sections[indexPath.section].expanded)")
if sections[indexPath.section].expanded {
return 88
} else {
return 0
}
}
I am adding an UIlabel to a cell in UITableView as below:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
let label = UILabel()
cell.contentView.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
label.leftAnchor.constraint(equalTo: cell.leftAnchor).isActive = true
label.topAnchor.constraint(equalTo: cell.topAnchor).isActive = true
label.widthAnchor.constraint(equalTo: cell.widthAnchor).isActive = true
label.heightAnchor.constraint(equalToConstant: 30).isActive = true
label.text = "row = \(indexPath.row)"
return cell
}
The above is working but cells are not properly showing the screen as sometime, the content of row1 is printed in another row.
If I add the below code, and when I click on a header of any section, the rows will be properly showing on the tableView, but just one time, I mean if I click one more time on the header, an error occurs inside CellForRowAt function (Thread 1: EXC_BAD_ACCESS (code=EXC_I386_GPFLT)):
cell.contentView.layer.sublayers?.forEach { $0.removeFromSuperlayer() }
Any advise?
EDIT:
just to explain how the sections are expanded, i will add the following:
protocol ExpandableHeaderViewDelegate {
func toggleSection(header: ExpandableHeaderView, section: Int)
}
class ExpandableHeaderView: UITableViewHeaderFooterView {
var delegate: ExpandableHeaderViewDelegate?
var section: Int!
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(selectHeaderAction)))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
#objc func selectHeaderAction(gestureRecognizer: UITapGestureRecognizer) {
let cell = gestureRecognizer.view as! ExpandableHeaderView
delegate?.toggleSection(header: self, section: cell.section)
}
func toggleSection(header: ExpandableHeaderView, section: Int) {
tableView.beginUpdates()
tableView.endUpdates()
}
}
My question was solved by [Knight0fDragon].
extension UIView
{
func clearSubviews()
{
for subview in self.subviews as! [UIView] {
subview.removeFromSuperview();
}
}
}
and then
cell.contentView.clearSubviews()
Thanks for all kind people for their support.
If the problem is just for mismatch of cell data then try using
override func prepareForReuse() {
super.prepareForReuse()
self.label.text = ""
}
Declare the UILabel in the cell's class with null value instead of declaring it in cellForRowAt
Try this inside cellForRowAt:
if tableView.rectForRow(at: indexPath).height == 0.0 {
return UITableViewCell()
}
It should be above all other code.
Try (call it before adding new label)
cell.contentView.subviews.removeAll()
instead of
cell.contentView.layer.sublayers?.forEach { $0.removeFromSuperlayer() }

Swift - How can I select multiple rows in tableview without segue

My development environment is swift3, xcode8.
I'm making a list app like Apple's message app.
When I select the list in the table view, I go to the detail page (through the seg) and now I want to implement multiple delete functions, but there's a problem. When I edit mode, I can see the selection window, but if I select that selection window, just go to the detail page.
Maybe before going to the detail page through Seg. I think I should make it a multiple choice. What should I do?
Make sure you conform something like below code;
class TableviewController:UITableViewController{
override func viewDidLoad() {
super.viewDidLoad()
var isMultipleSelectionActive = false
var selectedItems: [String: Bool] = [:]
tableView.allowsMultipleSelectionDuringEditing = true
tableView.setEditing(true, animated: false)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
cell.textLabel?.text = "\(indexPath.row)"
return cell
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let selectedItem = items.objectAtIndex(indexPath.row)
//add to selectedItems
selectedItems[selectedItem] = true
}
func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
let selectedItem = items.objectAtIndex(indexPath.row)
// remove from selectedItems
selectedItems[selectedItem] = nil
}
func getStatusOfSelectedItems() {
for item in selectedItems {
println(item)
}
}
//You should override shouldPerformSegueWithIdentifier and return false if isMultipleSelectionActive is true
override func shouldPerformSegue(withIdentifier identifier: String?, sender: Any?) -> Bool {
if let identifierName = identifier {
if identifierName == "NameOfYourSegueIdentifier" {
if isMultipleSelectionActive {
return false
}
}
}
return true
}
}
This code used to select the multiple row
class TableViewController: UITableViewController
{
var lastSelectedIndexPath = NSIndexPath(forRow: -1, inSection: 0)
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath)
// Configure the cell...
cell.textLabel!.text = "row: \(indexPath.row)"
if cell.selected
{
cell.selected = false
if cell.accessoryType == UITableViewCellAccessoryType.None
{
cell.accessoryType = UITableViewCellAccessoryType.Checkmark
}
else
{
cell.accessoryType = UITableViewCellAccessoryType.None
}
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
let cell = tableView.cellForRowAtIndexPath(indexPath)
if cell!.selected
{
cell!.selected = false
if cell!.accessoryType == UITableViewCellAccessoryType.None
{
cell!.accessoryType = UITableViewCellAccessoryType.Checkmark
}
else
{
cell!.accessoryType = UITableViewCellAccessoryType.None
}
}
}

Can't un check all cell before check one swift 2

I m using swift 2 and UITableViews and when I press a cell a checkmark appear, but I wan't that only one cell can be checked in my tableview so the other checkmarks will disappear from my tableview. I tried different technics without success. I have a CustomCell with just a label.
Here is my code :
import UIKit
class MyViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{
#IBOutlet weak var tableView: UITableView!
var answersList: [String] = ["One","Two","Three","Four","Five"]
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return answersList.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("MyCustomCell", forIndexPath: indexPath) as! MyCustomCell
cell.displayAnswers(answersList[indexPath.row]) // My cell is just a label
return cell
}
// Mark: Table View Delegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// Element selected in one of the array list
tableView.deselectRowAtIndexPath(indexPath, animated: true)
if let cell = tableView.cellForRowAtIndexPath(indexPath) {
if cell.accessoryType == .Checkmark {
cell.accessoryType = .None
} else {
cell.accessoryType = .Checkmark
}
}
}
}
Assuming you've only section here's what you can do
// checkmarks when tapped
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let section = indexPath.section
let numberOfRows = tableView.numberOfRowsInSection(section)
for row in 0..<numberOfRows {
if let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: row, inSection: section)) {
cell.accessoryType = row == indexPath.row ? .Checkmark : .None
}
}
}
Fixed code from #SirH to work with Swift 3
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let section = indexPath.section
let numberOfRows = tableView.numberOfRows(inSection: section)
for row in 0..<numberOfRows {
if let cell = tableView.cellForRow(at:IndexPath(row: row, section: section)) {
cell.accessoryType = row == indexPath.row ? .checkmark : .none
}
}
}