Trigger segue from a "collapsed" cell - ios

I made a table view with collapsing cells I followed this tutorial; everything works great, except for the segue method. I simply tried to add performsegueWithIdentifier method (adding the segue in the storyboard by the cell)
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
performSegueWithIdentifier("toChantController", sender: self)
}
and prepareForSegue method:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if segue.identifier == "toChantController"
{
let indexPath = tableView.indexPathForCell(sender as! UITableViewCell)
let controller = segue.destinationViewController as! ChantViewController
controller.chant = "\(sections[indexPath!.row])"
}
}
but Xcode sends me this error
"Could not cast value of type 'iSupporters.TeamChantViewController' (0x104562730) to 'UITableViewCell' (0x106600540)."
Here my whole class:
import UIKit
class TeamChantViewController: UIViewController, UITableViewDataSource, UITableViewDelegate
{
// MARK: properties
var teamChants: TeamModel!
#IBOutlet weak var tableView: UITableView!
struct Section {
var name: String!
var items: [String]!
var collapsed: Bool!
init(name: String, items: [String], collapsed: Bool = true) {
self.name = name
self.items = items
self.collapsed = collapsed
}
}
var sections = [Section]()
override func viewDidLoad()
{
super.viewDidLoad()
tableView.backgroundColor = UIColor.clearColor()
tableView.separatorColor = UIColor.clearColor()
sections = [
Section(name: "Juventus", items: ["Olè", "fino alla fine", "ovunque voi giocate", "juve olè"]),
Section(name: "Derby", items: ["toro merda", "odio i granata", "il viola è il colore che odio"]),
Section(name: "Giocatori", items: ["Vidal", "Pogba", "Del Piero"])
]
}
override func viewWillAppear(animated: Bool)
{
super.viewWillAppear(animated)
self.tabBarController?.tabBar.hidden = true
}
// MARK: collection view data source and delegate
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
var count = sections.count
for section in sections
{
count += section.items.count
}
return count
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
let section = getSectionIndex(indexPath.row)
let row = getRowIndex(indexPath.row)
if row == 0 {
return 50.0
}
return sections[section].collapsed! ? 0 : 44.0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let section = getSectionIndex(indexPath.row)
let row = getRowIndex(indexPath.row)
if row == 0
{
let cell = tableView.dequeueReusableCellWithIdentifier("teamChantsHeader") as! TeamChantsHeader
cell.teamChantSectionTitle.text = sections[section].name
cell.toggleButton.tag = section
cell.toggleButton.setTitle(sections[section].collapsed! ? "+" : "-", forState: .Normal)
cell.toggleButton.addTarget(self, action: #selector(TeamChantViewController.toggleCollapse), forControlEvents: .TouchUpInside)
return cell
} else {
let cell = tableView.dequeueReusableCellWithIdentifier("teamChantsCell") as UITableViewCell!
cell.textLabel?.text = sections[section].items[row - 1]
return cell
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
performSegueWithIdentifier("toChantController", sender: self)
print(self)
}
// MARK: navigation (segue)
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if segue.identifier == "toChantController"
{
let indexPath = tableView.indexPathForCell(sender as! UITableViewCell)
let controller = segue.destinationViewController as! ChantViewController
controller.chant = "\(sections[indexPath!.row])"
}
}
// MARK: - other methods
func toggleCollapse(sender: UIButton)
{
let section = sender.tag
let collapsed = sections[section].collapsed
// Toggle collapse
sections[section].collapsed = !collapsed
let indices = getHeaderIndices()
let start = indices[section]
let end = start + sections[section].items.count
tableView.beginUpdates()
for i in start ..< end + 1
{
tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: i, inSection: 0)], withRowAnimation: .Automatic)
}
tableView.endUpdates()
}
func getSectionIndex(row: NSInteger) -> Int
{
let indices = getHeaderIndices()
for i in 0..<indices.count
{
if i == indices.count - 1 || row < indices[i + 1]
{
return i
}
}
return -1
}
func getRowIndex(row: NSInteger) -> Int
{
var index = row
let indices = getHeaderIndices()
for i in 0..<indices.count
{
if i == indices.count - 1 || row < indices[i + 1]
{
index -= indices[i]
break
}
}
return index
}
func getHeaderIndices() -> [Int]
{
var index = 0
var indices: [Int] = []
for section in sections
{
indices.append(index)
index += section.items.count + 1
}
return indices
}
}
Could anyone help me to perform this segue?
Edit: my segue in the storyboard

You are doing here two things,
First you have created segue in stroyboard from the UITableViewCell to ChantViewController.
Now in didSelectRowAtIndexPath you are performing segue again with passing self as reference of TeamChantViewController.
You need to change any one thing to solved your problem.
Edit: From your comment you need to pass indexPath object with sender parameter in performSegue method like this and get that indexPath in prePareForSegue method.
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier("toChantController", sender: indexPath)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "toChantController"
{
let indexPath = sender as! NSIndexPath
let controller = segue.destinationViewController as! ChantViewController
controller.chant = "\(sections[indexPath!.row])"
}
}

Related

How do I increment/decrement a label value with two buttons pressed in tableview Swift [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I need swift code in my ViewController one table view, label, AddButton. In tableview 8 customcells are there, in each cell one label,(-, +) buttons are there. If I press '+' label value must increase while if I press '-' label value decrease, same way happen to each and every cell. Finally, if I press AddButton the total must be added and it displays in a label in viewcontroller Thanks, InAdvance. image
in viewController tableview methods
#IBOutlet var tableviewObj: UITableView!
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return 8
}
public func numberOfSections(in tableView: UITableView) -> Int // Default is 1 if not implemented
{
return 1
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
if indexPath.row == 0 {
let cell:firstTableViewCell = tableView.dequeueReusableCell(withIdentifier: "first") as! firstTableViewCell
return cell
}
else if indexPath.row == 1 {
let cell:secondTableViewCell = tableView.dequeueReusableCell(withIdentifier: "second") as! secondTableViewCell
return cell
}
else if indexPath.row == 2 {
let cell:thirdTableViewCell = tableView.dequeueReusableCell(withIdentifier: "third") as! thirdTableViewCell
return cell
}
else if indexPath.row == 3 {
let cell:fourthTableViewCell = tableView.dequeueReusableCell(withIdentifier: "fourth") as! fourthTableViewCell
return cell
}
else if indexPath.row == 4 {
let cell:fifthTableViewCell = tableView.dequeueReusableCell(withIdentifier: "fifth") as! fifthTableViewCell
return cell
}
else if indexPath.row == 5 {
let cell:sixthTableViewCell = tableView.dequeueReusableCell(withIdentifier: "sixth") as! sixthTableViewCell
return cell
}
else if indexPath.row == 6 {
let cell:seventhTableViewCell = tableView.dequeueReusableCell(withIdentifier: "seven") as! seventhTableViewCell
return cell
}else {
let cell:eighthTableViewCell = tableView.dequeueReusableCell(withIdentifier: "eight") as! eighthTableViewCell
return cell
}
}
#IBOutlet var labelObj: UILabel!
#IBAction func Total(_ sender: Any) {
// i need code here
}
class firstTableViewCell: UITableViewCell {
#IBOutlet var labelObj: UILabel!
var cur = 0
var str = ""
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
#IBAction func Minus(_ sender: Any) {
if (self.labelObj.text == "1") {
self.labelObj.text = String( 1)
}else
{
cur = Int(labelObj.text!)!
self.labelObj.text = String(cur - 1)
str = self.labelObj.text!
print(str)
}
}
#IBAction func Add(_ sender: Any) {
cur = Int(labelObj.text!)!
self.labelObj.text = String(cur + 1)
str = self.labelObj.text!
print(str)
}
Create a model to hold the value of the label in a cell-like below
struct Product {
var price = 0
}
We need to communicate from cell to viewcontroller so we need a protocol like a below
protocol CartSelection {
func addProductToCart(product : Product, atindex : Int)
}
I have created array to show in tableview. And I will pass the product to cell. So ViewController code is :
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,CartSelection {
#IBOutlet weak var totalLabel: UILabel!
var productArray = [Product]()
#IBOutlet weak var testTableview: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
for _ in 0...10{
productArray.append(Product(price: 1))
}
testTableview.allowsSelection = false
calculateTotal()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return productArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell : TestTableViewCell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TestTableViewCell
cell.product = productArray[indexPath.row]
cell.valueLabel.text = "\(cell.product.price)"
cell.productIndex = indexPath.row
cell.cartSelectionDelegate = self
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 75
}
#IBAction func addBtnPressed(_ sender: UIButton) {
}
func addProductToCart(product: Product, atindex: Int) {
productArray[atindex] = product
calculateTotal()
}
func calculateTotal()
{
var totalValue = 0
for objProduct in productArray {
totalValue += objProduct.price
}
self.totalLabel.text = "Total \(totalValue)"
}
}
and TableViewCell code like below :
class TestTableViewCell: UITableViewCell {
var product : Product!
private var counterValue = 1
var productIndex = 0
var cartSelectionDelegate: CartSelection?
#IBOutlet weak var valueLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
#IBAction func minusButton(_ sender: UIButton) {
if(counterValue != 1){
counterValue -= 1;
}
self.valueLabel.text = "\(counterValue)"
product.price = counterValue
cartSelectionDelegate?.addProductToCart(product: product, atindex: productIndex)
}
#IBAction func plusButton(_ sender: UIButton){
counterValue += 1;
self.valueLabel.text = "\(counterValue)"
product.price = counterValue
cartSelectionDelegate?.addProductToCart(product: product, atindex: productIndex)
}
}
Output will look like the screenshot below
Initial Stage
After changing value in cell

Segue not working in Swift

I'm trying to pass a certain part of an array to another view controller based on which tableview cell you click on. So when I click on the third cell for example, it'll send the array data from the third cell to the next screen. This data is an array called "todos". When I try to receive the data in the next screen, there is no data.
Code:
func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "EditTodo" {
print("it is")
var vc = segue.destination as! ViewController
// var indexPath = tableView.indexPathForCell(sender as UITableViewCell)
var indexPath = tableView.indexPathForSelectedRow
if let index = indexPath {
vc.todo = todos[index.row]
}
}
}
I'm not sure if it's being called at all, or what. The identifier is correct, and I'm not sure what else to do. (When I run it, the print function is not called, but I'm not even sure if it's supposed to be).
Here is the whole page of code from the 'sending data' page with the table:
import UIKit
var todos: [TodoModel] = []
var filteredTodos: [TodoModel] = []
class HomeViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchDisplayDelegate {
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewDidAppear(_ animated: Bool) {
print("i think it worked...")
let defaults = UserDefaults.standard
if todos.count > 0 {
// Save what we have
let data = NSKeyedArchiver.archivedData(withRootObject: todos)
defaults.set(data, forKey: "TDDATA")
defaults.synchronize()
print("saved \(todos.count)")
} else if let storedTodoData = defaults.data(forKey: "TDDATA"),
let storedTodos = NSKeyedUnarchiver.unarchiveObject(with: storedTodoData) as? [TodoModel] {
// There was stored data! Use it!
todos = storedTodos
print("Used \(todos.count) stored todos")
tableView.reloadData()
self.tableView.tableFooterView = UIView()
}
//print([todos.first])
print("Here?: \(todos.first?.title)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override var prefersStatusBarHidden: Bool {
return true
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == searchDisplayController?.searchResultsTableView {
return filteredTodos.count
}
else {
return todos.count
}
}
// Display the cell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Must use 'self' here because searchResultsTableView needs to reuse the same cell in self.tableView
let cell = self.tableView.dequeueReusableCell(withIdentifier: "todoCell")! as UITableViewCell
var todo : TodoModel
if tableView == searchDisplayController?.searchResultsTableView {
todo = filteredTodos[indexPath.row] as TodoModel
}
else {
todo = todos[indexPath.row] as TodoModel
}
//var image = cell.viewWithTag(101) as! UIImageView
var title = cell.viewWithTag(102) as! UILabel
var date = cell.viewWithTag(103) as! UILabel
//image.image = todo.image
// image = UIImageView(image: newImage)
// if image.image == nil{
// print("nilish")
// image = UIImageView(image: UIImage(named: "EmptyProfile.png"))
// }
// image.image = todo.image
// if image.image == nil{
// print("pic is nil")
// image.image = UIImage(named: "CopyEmptyProfilePic.jpg")
// }
title.text = todo.title
date.text = "\(NSDate())"
let locale = NSLocale.current
let dateFormat = DateFormatter.dateFormat(fromTemplate: "yyyy-MM-dd", options:0, locale:locale)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateFormat
return cell
}
// MARK - UITableViewDelegate
// Delete the cell
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.delete {
todos.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath as IndexPath], with: UITableViewRowAnimation.automatic)
let defaults = UserDefaults.standard
if todos.count >= 0 {
// Save what we have
let data = NSKeyedArchiver.archivedData(withRootObject: todos)
defaults.set(data, forKey: "TDDATA")
defaults.synchronize()
print("saved \(todos.count)")
} else if let storedTodoData = defaults.data(forKey: "TDDATA"),
let storedTodos = NSKeyedUnarchiver.unarchiveObject(with: storedTodoData) as? [TodoModel] {
// There was stored data! Use it!
todos = storedTodos
print("Used \(todos.count) stored todos")
}
tableView.reloadData()
}
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 80
}
// Edit mode
override func setEditing(_ editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
tableView.setEditing(editing, animated: true)
}
// Move the cell
func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return self.isEditing
}
// func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
// let todo = todos.removeAtIndex(sourceIndexPath.row)
//todos.insert(todo, atIndex: destinationIndexPath.row)
// }
// MARK - UISearchDisplayDelegate
// Search the Cell
func searchDisplayController(controller: UISearchDisplayController, shouldReloadTableForSearchString searchString: String?) -> Bool {
//filteredTodos = todos.filter({( todo: TodoModel) -> Bool in
// let stringMatch = todo.title.rangeOfString(searchString)
// return stringMatch != nil
//})
// Same as below
filteredTodos = todos.filter(){$0.title.range(of: searchString!)
!= nil}
return true
}
// MARK - Storyboard stuff
// Unwind
#IBAction func close(segue: UIStoryboardSegue) {
print("closed!")
tableView.reloadData()
}
// Segue
func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "EditTodo" {
print("it is")
var vc = segue.destination as! ViewController
// var indexPath = tableView.indexPathForCell(sender as UITableViewCell)
var indexPath = tableView.indexPathForSelectedRow
if let index = indexPath {
vc.todo = todos[index.row]
}
}
}
}
How I am receiving the data in viewDidLoad of receiving screen:
nameOfDocTF.delegate = self
nameOfDocTF.text = todo?.title
outputTextView.attributedText = todo?.desc
print(todo?.title)
//prints "nil"
As I suspected you´re missing the didSelectRowAt function which will be called when you click on a cell and from there you need to call your prepareForSegue. Implement the following function and try:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.performSegue(withIdentifier: "EditTodo", sender: indexPath.row)
}
And then replace your prepareForSegue function with the following:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "EditTodo" {
let vc = segue.destination as! ViewController
if let index = sender as? Int {
vc.todo = todos[index]
}
}
}

found nil while trying to segue away from a tableView

I'm getting errors whenever I try to reference the viewTable in the viewDidLoad AFTER I click on a cell to transition with the segue. Thanks a lot!!
Basically I can't use the segue unless I comment out the tableview references in view did load... but I need those in order to use the search bar and im sure it will cause problems on the way back...
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet var tableView: UITableView! {
didSet {
print("tableView is set")
}
}
let searchController = UISearchController(searchResultsController: nil)
let textCellIdentifier = "TextCell"
var buildings: [(String,String)] = []
var filteredBuildings = [(String,String)]()
var goToIndex: Int?
override func viewDidLoad() {
super.viewDidLoad()
print(tableView)
var buildingTuples = loadBuildings()
for tuple in buildingTuples {
self.buildings.append(tuple)
}
self.goToIndex = -1
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
definesPresentationContext = true
tableView!.tableHeaderView = searchController.searchBar
}
func filterContentForSearchText(searchText: String, scope: String = "All") {
filteredBuildings = buildings.filter { building in
return building.0.lowercaseString.containsString(searchText.lowercaseString)
}
self.tableView.reloadData()
}
// MARK: UITextFieldDelegate Methods
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//return self.buildings.count
if searchController.active && searchController.searchBar.text != "" {
return filteredBuildings.count
}
return buildings.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
/*
let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath)
let row = indexPath.row
cell.textLabel?.text = buildings[row].0
return cell
*/
let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath)
let tuple: (String, String)
if searchController.active && searchController.searchBar.text != "" {
tuple = filteredBuildings[indexPath.row]
} else {
tuple = buildings[indexPath.row]
}
cell.textLabel?.text = tuple.0
return cell
}
// MARK: UITableViewDelegate Methods
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//tableView.deselectRowAtIndexPath(indexPath, animated: true)
let row = indexPath.row
self.goToIndex = indexPath.row
self.performSegueWithIdentifier("MainToLocation", sender: self)
//print(buildings[row].0)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "MainToLocation" {
let locationViewController = (segue.destinationViewController as! LocationViewController)
locationViewController.building = self.buildings[self.goToIndex!]
}
}
extension ViewController: UISearchResultsUpdating {
func updateSearchResultsForSearchController(searchController: UISearchController) {
filterContentForSearchText(searchController.searchBar.text!)
}
}
You can try this..
let destinationVC = self.storyboard!.instantiateViewControllerWithIdentifier("viewController") as! NextViewController
var alreadyPushed = false
if let vc = self.navigationController?.viewControllers {
for viewController in vc {
if let viewController = viewController as? NextViewController {
self.navigationController?.popToViewController(viewController, animated: true)
print("Push your controller")
alreadyPushed = true
break
}
}
}
if alreadyPushed == false {
self.navigationController?.pushViewController(destinationVC, animated: true)
}

how to uncheck uitableview cells using accessory checkmark

i have two sections
1.MapViewController
2.TypesTableViewController
when i run my app and call TypesTableViewController and when it opens it shows all cells selected i want it to be unchecked
please help me and check my code
1.MapViewController
class MapViewController: UIViewController {
#IBOutlet weak var mapCenterPinImage: UIImageView!
#IBOutlet weak var pinImageVerticalConstraint: NSLayoutConstraint!
var searchedTypes = ["bakery", "bar", "cafe", "grocery_or_supermarket", "restaurant"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "Types Segue" {
let navigationController = segue.destinationViewController as! UINavigationController
let controller = navigationController.topViewController as! TypesTableViewController
controller.selectedTypes = searchedTypes
controller.delegate = self
}
}
}
// MARK: - TypesTableViewControllerDelegate
extension MapViewController: TypesTableViewControllerDelegate {
func typesController(controller: TypesTableViewController, didSelectTypes types: [String]) {
searchedTypes = controller.selectedTypes.sort()
dismissViewControllerAnimated(true, completion: nil)
}
}
2.TypesTableViewController
protocol TypesTableViewControllerDelegate: class {
func typesController(controller: TypesTableViewController, didSelectTypes types: [String])
}
class TypesTableViewController: UITableViewController {
let possibleTypesDictionary = ["bakery":"Bakery", "bar":"Bar", "cafe":"Cafe", "grocery_or_supermarket":"Supermarket", "restaurant":"Restaurant"]
var selectedTypes: [String]!
weak var delegate: TypesTableViewControllerDelegate!
var sortedKeys: [String] {
return possibleTypesDictionary.keys.sort()
}
// MARK: - Actions
#IBAction func donePressed(sender: AnyObject) {
delegate?.typesController(self, didSelectTypes: selectedTypes)
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return possibleTypesDictionary.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("TypeCell", forIndexPath: indexPath)
let key = sortedKeys[indexPath.row]
let type = possibleTypesDictionary[key]!
cell.textLabel?.text = type
cell.imageView?.image = UIImage(named: key)
cell.accessoryType = (selectedTypes!).contains(key) ? .Checkmark : .None
return cell
}
// MARK: - Table view delegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let key = sortedKeys[indexPath.row]
if (selectedTypes!).contains(key) {
selectedTypes = selectedTypes.filter({$0 != key})
} else {
selectedTypes.append(key)
}
tableView.reloadData()
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//toggle checkmark on and off
if tableView.cellForRow(at: indexPath)?.accessoryType == .checkmark {
tableView.cellForRow(at: indexPath)?.accessoryType = .none
}
else {
tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
}
//add animation so cell does not stay selected
tableView.deselectRow(at: indexPath, animated: true)
}
Not sure what you are doing in your code. If you want to uncheck then change below line to
cell.accessoryType = (selectedTypes!).contains(key) ? .Checkmark : .None
to
cell.accessoryType = (selectedTypes!).contains(key) ? . None : . Checkmark
Updated:- second part of the answer to get only checkmark cells,
change as below
#IBAction func donePressed(sender: AnyObject) {
let rowCount = tableView.numberOfRowsInSection(0)
selectedTypes.removeAll()
for var index = 0; index < rowCount; ++index {
let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: index, inSection: 0)) as! YourCell
if cell.accessoryType = .Checkmark{
let key = sortedKeys[index]
selectedTypes.append(key)
}
delegate?.typesController(self, didSelectTypes: selectedTypes)
}
}

Getting error in handling the selected row in table in iOS swift

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("SearchTableViewCellIdentifier") as! SearchTableViewCell
var item = self.searchResult[indexPath.row] as? PFObject
cell.post = item
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndex rowIndex: Int)
{
let indexPath = tableView.indexPathForSelectedRow()
let currentCell = tableView.cellForRowAtIndexPath(indexPath!)! as UITableViewCell
println(currentCell.textLabel!.text)
}
I am not getting the actual value. I am getting nil on printing currentCell.textLabel!.text
just remove override
class yourclassName: UIViewController, UITableViewDataSource, UITableViewDelegate
var cod: AnyObject?
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
}
func tableView(tableView: UITableView, didSelectRowAtIndex rowIndex: Int)
{
//Handle row selection
// choice 1
let indexPath = tableView.indexPathForSelectedRow();
// if it is not work follow second option
cod = self.searchResult[indexPath.row] as? PFObject
// choice 2
cod = self.searchResult[rowIndex] as? PFObject
println(cod)
self.performSegueWithIdentifier("yourSegueName", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if (segue.identifier == "yourSegueName") {
var svc = segue!.destinationViewController as secondViewController;
svc.toPass = cod
}
}
in your second VC create this string
var toPass:String!

Resources