I was trying iterating through all cell in TableView and delete them. I call function DeleteAll:
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var myTableView: UITableView!
#IBAction func DeleteAll(sender: UIButton) {
//myTableView.reloadData()
for j in 0..<myTableView.numberOfSections {
for i in (myTableView.numberOfRowsInSection(j) - 1).stride(through: 0, by: -1) {
let myIndexPath = NSIndexPath(forRow: i, inSection: j)
print("I=" + String(i) + "section " + String(j))
self.tableView( myTableView, commitEditingStyle: UITableViewCellEditingStyle.Delete, forRowAtIndexPath: myIndexPath)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
var indexPathForSelectedRows = [NSIndexPath]()
lazy var productLines: [ProductLine] = {
return ProductLine.productLines()
}()
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
let selctedRow = tableView.cellForRowAtIndexPath(indexPath)!
if editingStyle == UITableViewCellEditingStyle.Delete {
productLines[indexPath.section].products.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
selctedRow.accessoryType = UITableViewCellAccessoryType.None
}
}
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
let delete = UITableViewRowAction(style: .Destructive, title: "Delete") { (action, indexPath) in
self.tableView( tableView, commitEditingStyle: UITableViewCellEditingStyle.Delete, forRowAtIndexPath: indexPath)
}
let share = UITableViewRowAction(style: .Normal, title: "Disable") { (action, indexPath) in
}
delete.backgroundColor = UIColor.blackColor()
share.backgroundColor = UIColor.blueColor()
return [delete, share]
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//self.tableView( tableView, commitEditingStyle: UITableViewCellEditingStyle.Delete, forRowAtIndexPath: indexPath)
let row = tableView.cellForRowAtIndexPath(indexPath)!
if row.accessoryType == UITableViewCellAccessoryType.None {
row.accessoryType = UITableViewCellAccessoryType.Checkmark
}
else {
row.accessoryType = UITableViewCellAccessoryType.None
}
}
// MARK: - Table view data source
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let productLine = productLines[section]
return productLine.name
}
//override func tableV
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return productLines.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
let productLine = productLines[section]
return productLine.products.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("uppercaseString", forIndexPath: indexPath)
let productLine = productLines[indexPath.section]
let product = productLine.products[indexPath.row]
cell.textLabel?.text = product.title
cell.detailTextLabel?.text = product.description
cell.imageView?.image = product.image
// Configure the cell...
return cell
}
}
But I have had this error, and I don't find out what wrong. This is console log:
I=3section 0
I=2section 0
I=1section 0
I=0section 0
I=8section 1
fatal error: unexpectedly found nil while unwrapping an Optional
value (lldb)
Yes, that will return nil if the row isn't on screen, so force
unwrapping is a bad idea. In fact calling the delegate methods
yourself is a bad idea. If you want to reuse code then you should have
your delegate method calla delete method. You can't retrieve all
cells; you can only retrieve cells that are onscreen. You shouldn't
need to retrieve all cells; you simply update your data model and have
the table reflect those changes by reloading the table, reloading
specific rows or inserting/deleting specific rows
– Paulw11
Related
I have attached the image click the card view expands the same card inside the table cell dynamically its passible to achieve this?
I have searched a lot but not working
Hear my code added header cell with CardView
added arrow button to click the button expand the cell
its able expand but not in parent card it was showing diff card
I have adde my source code
var hiddenSections = Set<Int>()
let tableViewData = [
["1","2","3","4","5"],
["1","2","3","4","5"],
["1","2","3","4","5"],
]
override func viewDidLoad() {
super.viewDidLoad()
let CustomeHeaderNib = UINib(nibName: "CustomSectionHeader", bundle: Bundle.main)
historyTableView.register(CustomeHeaderNib, forHeaderFooterViewReuseIdentifier: "customSectionHeader")
}
func numberOfSections(in tableView: UITableView) -> Int {
return self.tableViewData.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if self.hiddenSections.contains(section) {
return 0
}
return self.tableViewData[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = self.tableViewData[indexPath.section][indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return view.frame.width/4
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = self.historyTableView.dequeueReusableHeaderFooterView(withIdentifier: "customSectionHeader") as! CustomSectionHeader
header.setupCornerRadious()
let sectionButton = header.expandBtn
sectionButton?.setTitle(String(section),
for: .normal)
sectionButton?.tag = section
sectionButton?.addTarget(self,action: #selector(self.hideSection(sender:)), for: .touchUpInside)
return header
}
#objc
private func hideSection(sender: UIButton) {
let section = sender.tag
func indexPathsForSection() -> [IndexPath] {
var indexPaths = [IndexPath]()
for row in 0..<self.tableViewData[section].count {
indexPaths.append(IndexPath(row: row,
section: section))
}
return indexPaths
}
if self.hiddenSections.contains(section) {
self.hiddenSections.remove(section)
self.historyTableView.insertRows(at: indexPathsForSection(),
with: .fade)
} else {
self.hiddenSections.insert(section)
self.historyTableView.deleteRows(at: indexPathsForSection(),
with: .fade)
}
}
With out sections also you can achieve this. To do this,
1.Return cell height as section height. If user clicks on the cell then return total content height to the particular cell.
2.You need to take an array, if user selects cell, add indexPath number in to array. If selects already expand cell remove it from array. In height for row at index check indexPath is in array or not.
This is one of the way. With sections also you can do that.
//MARK:- UITableView Related Methods
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrDict.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
// var cel = tblExpandedTest.dequeueReusableCellWithIdentifier("expCell", forIndexPath: indexPath) as! CDTableViewCell
var cel : CaseHearingTabTVC! = tableView.dequeueReusableCell(withIdentifier: "caseHearingTabCell") as! CaseHearingTabTVC
if(cel == nil)
{
cel = Bundle.main.loadNibNamed("caseHearingTabCell", owner: self, options: nil)?[0] as! CaseHearingTabTVC;
}
//cell?.backgroundColor = UIColor.white
cel.delegate = self
if indexPath != selctedIndexPath{
cel.subview_desc.isHidden = true
cel.subview_remarks.isHidden = true
cel.lblHearingTime.isHidden = true
}
else {
cel.subview_desc.isHidden = false
cel.subview_remarks.isHidden = false
cel.lblHearingTime.isHidden = false
}
return cel
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectIndex = true;
if(selectedInd == indexPath.row) {
selectedInd = -1
}
else{
let currentCell = tableView.cellForRow(at: indexPath)! as! CaseHearingTabTVC
cellUpdatedHeight = Float(currentCell.lblHearingTime.frame.origin.y + currentCell.lblHearingTime.frame.size.height) + 2;
selectedInd = -1
tblCaseHearing.reloadData()
selectedInd = indexPath.row
}
let previousPth = selctedIndexPath
if indexPath == selctedIndexPath{
selctedIndexPath = nil
}else{
selctedIndexPath = indexPath
}
var indexPaths : Array<IndexPath> = []
if let previous = previousPth{
indexPaths = [previous]
}
if let current = selctedIndexPath{
indexPaths = [current]
}
if indexPaths.count>0{
tblCaseHearing.reloadRows(at: indexPaths, with: UITableView.RowAnimation.automatic)
}
}
func tableView(_ tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowIndexPath indexPath:IndexPath) {
(cell as! CaseHearingTabTVC).watchFrameChanges()
}
func tableView(_ tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowIndexPath indexPath:IndexPath) {
(cell as! CaseHearingTabTVC).ignoreFrameChanges()
}
func tableView(_ TableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
if indexPath == selctedIndexPath{
return CGFloat(cellUpdatedHeight)
}else{
return CaseHearingTabTVC.defaultHeight
}
}
Best approach is to create two different cells for normal card and expanded card.
fileprivate var selectedIndex: Int?
func registerTableViewCells() {
tableView.register(UINib(nibName:Nib.CardCell , bundle: nil), forCellReuseIdentifier: "CardCell")
tableView.register(UINib(nibName:Nib.ExpandedCardCell , bundle: nil), forCellReuseIdentifier: "ExpandedCardCell")
}
override func viewDidLoad() {
super.viewDidLoad()
self.registerTableViewCells()
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
guard let index = selectedIndex else {
return 115
}
if index == indexPath.row{
return 200
}
return 115
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let selected = selectedIndex, selected == indexPath.row{
let cell = tableView.dequeueReusableCell(withIdentifier: "ExpandedCardCell", for: indexPath) as! ExpandedCardCell
return cell
}
let cell = tableView.dequeueReusableCell(withIdentifier: "CardCell", for: indexPath) as! CardCell
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if selectedIndex == indexPath.row{
selectedIndex = nil
}
else{
selectedIndex = indexPath.row
}
UIView.performWithoutAnimation {
tableView.reloadData()
}
}
I have one UIPickerView and one label inside expandable UITableViewCell and in the code I made 1 section and 3 cells all like first cell.
I did manage the data for every cell but my problem is when I select something from the first picker and I go to second picker and select something , my fist selection will be changed to same row order from the second picker .
To make it short how can I make the 3 pickers separate from each other and change every cell's label to the selected row from the same cell not else
This is a screenshot to my view :
And this my code :
import UIKit
let cellID = "cell"
class callViewController: UITableViewController {
var selectedIndexPath : NSIndexPath?
var tapped = false // when the first cell tapped it will be true
var flag = true
// These strings will be the data for the table view cells
let sections: [String] = ["Department:", "Team:", "Service:"]
override func awakeFromNib() {
super.awakeFromNib()
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
//number of sections
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
// header for the secation
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Required Info:"
}
//number of rows in section
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
//get the cell
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier(cellID, forIndexPath: indexPath) as! callCustomCell
cell.titleLabel.text=self.sections[indexPath.row]
// now reload the appropriate pickerData
if indexPath.row == 0{
cell.inputArrry=cell.departments
cell.picker.reloadAllComponents()
}
else if indexPath.row == 1{
cell.inputArrry=cell.teams
cell.picker.reloadAllComponents()
}
else if indexPath.row == 2{
cell.inputArrry=cell.services
cell.picker.reloadAllComponents()
}
if indexPath.row != 0{
cell.userInteractionEnabled = tapped
if (!tapped){
cell.backgroundColor=UIColor.clearColor()
}
else {
cell.backgroundColor=UIColor.whiteColor()
}
}
if indexPath.row==0{
cell.backgroundColor=UIColor.whiteColor()
cell.userInteractionEnabled=true
}
return cell
}
// method to run when table view cell is tapped
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.row == 0 && flag {
flag = false
tapped = true
tableView.reloadRowsAtIndexPaths([
NSIndexPath(forRow: 1, inSection: 0),
NSIndexPath(forRow: 2, inSection: 0)], withRowAnimation: .Automatic)
}
let previousIndexPath = selectedIndexPath
if indexPath == selectedIndexPath {
selectedIndexPath = nil
}
else {
selectedIndexPath = indexPath
}
var indexPaths : Array<NSIndexPath> = []
if let previous = previousIndexPath {
indexPaths += [previous]
}
if let current = selectedIndexPath {
indexPaths += [current]
}
if indexPaths.count > 0 {
tableView.reloadRowsAtIndexPaths(indexPaths, withRowAnimation: UITableViewRowAnimation.Automatic)
}
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
(cell as! callCustomCell).watchFrameChanges()
}
override func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
(cell as! callCustomCell).ignoreFrameChanges()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
for cell in tableView.visibleCells as! [callCustomCell] {
cell.ignoreFrameChanges()
}
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath == selectedIndexPath {
return callCustomCell.expandedHeight
} else {
return callCustomCell.defaultHeight
}
}
}
Use tags in the attribute inspector tab in the storyboards and then make if statements to change what is returned
if (pickerView.tag == 0) {
// Do something
} else if (pickerView.tag == 1 {
// Do something
} else {
// Do something
}
You could even use a switch statement too. Might look cleaner.
I'm trying to create a reorder indicator. So what I'm trying to do is that when the user is dragging the cell. That on the place the user wants to drop the cell an other cell is added with a background. I already achieved that. But when the user drops the cell, the indicator cell needs to be deleted and the table must stay the same like the user intended to.
Now I have the following problem. When the user drops the cell. The indicator cell is correctly removed but the dropped cell is behind another cell suddenly.
Screenshots to clarify:
My code:
import UIKit
import PureLayout
class ViewController: UIViewController {
lazy var tableView: UITableView = {
let tableView = UITableView(forAutoLayout: ())
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .SingleLine
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Default")
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Indicator")
tableView.tableFooterView = UIView()
return tableView
}()
private var data: [Int] = [Int]()
private var isIndicatorRowAddedInSection: Bool = false
private var lastIndicatorRowIndexPath: NSIndexPath?
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(self.tableView)
self.tableView.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsZero, excludingEdge: .Top)
self.tableView.autoPinEdgeToSuperviewEdge(.Top, withInset: 40)
for index in 0..<20 {
data.append(index)
}
self.tableView.editing = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController: UITableViewDelegate {
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 44
}
func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
}
func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
if let lastIndexPath = self.lastIndicatorRowIndexPath {
print("Need to delete a row on section \(lastIndexPath.section) row \(lastIndexPath.row)")
self.isIndicatorRowAddedInSection = false
self.lastIndicatorRowIndexPath = nil
tableView.beginUpdates()
tableView.deleteRowsAtIndexPaths([lastIndexPath], withRowAnimation: .Fade)
tableView.endUpdates()
}
let itemToMove = self.data[fromIndexPath.row]
self.data.removeAtIndex(fromIndexPath.row)
self.data.insert(itemToMove, atIndex: toIndexPath.row)
}
func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
return .None
}
func tableView(tableView: UITableView, shouldIndentWhileEditingRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
func tableView(tableView: UITableView, targetIndexPathForMoveFromRowAtIndexPath sourceIndexPath: NSIndexPath,
toProposedIndexPath proposedDestinationIndexPath: NSIndexPath) -> NSIndexPath {
if let lastIndexPath = self.lastIndicatorRowIndexPath {
print("Target indexpath indexpath to delete row \(lastIndexPath.section) row \(lastIndexPath.row)")
self.isIndicatorRowAddedInSection = false
tableView.beginUpdates()
tableView.deleteRowsAtIndexPaths([lastIndexPath], withRowAnimation: .Fade)
tableView.endUpdates()
self.lastIndicatorRowIndexPath = nil
}
self.isIndicatorRowAddedInSection = true
self.lastIndicatorRowIndexPath = proposedDestinationIndexPath
tableView.beginUpdates()
print("Indicator view inserted at section \(proposedDestinationIndexPath.section) row \(proposedDestinationIndexPath.row)")
tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: proposedDestinationIndexPath.row, inSection: proposedDestinationIndexPath.section)], withRowAnimation: .Automatic)
tableView.endUpdates()
return proposedDestinationIndexPath
}
}
extension ViewController: UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if self.isIndicatorRowAddedInSection {
return self.data.count + 1
}
return self.data.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if let indicatorIndexPath = self.lastIndicatorRowIndexPath where isIndicatorRowAddedInSection {
if indicatorIndexPath.section == indexPath.section && indicatorIndexPath.row == indexPath.row {
let cell = tableView.dequeueReusableCellWithIdentifier("Indicator", forIndexPath: indexPath)
return cell
}
}
let cell = tableView.dequeueReusableCellWithIdentifier("Default", forIndexPath: indexPath)
cell.textLabel?.text = String(self.data[indexPath.row])
return cell
}
}
I don't see the problem. Can someone help me?
I found the problem. In the moveRow it is executed on Thread 1 (main thread) but it seems like it's not. Because when you wrap it with a dispatch async to the main thread it just works.
Full working code:
import UIKit
import PureLayout
class ViewController: UIViewController {
lazy var tableView: UITableView = {
let tableView = UITableView(forAutoLayout: ())
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .SingleLine
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Default")
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Indicator")
tableView.tableFooterView = UIView()
return tableView
}()
private var data: [Int] = [Int]()
private var isIndicatorRowAddedInSection: Bool = false
private var lastIndicatorRowIndexPath: NSIndexPath?
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(self.tableView)
self.tableView.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsZero, excludingEdge: .Top)
self.tableView.autoPinEdgeToSuperviewEdge(.Top, withInset: 40)
for index in 0..<5 {
data.append(index)
}
self.tableView.editing = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController: UITableViewDelegate {
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 44
}
func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
}
func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
let itemToMove = self.data[fromIndexPath.row]
self.data.removeAtIndex(fromIndexPath.row)
self.data.insert(itemToMove, atIndex: toIndexPath.row - 1)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if let lastIndexPath = self.lastIndicatorRowIndexPath {
print("Need to delete a row on section \(lastIndexPath.section) row \(lastIndexPath.row)")
self.isIndicatorRowAddedInSection = false
self.lastIndicatorRowIndexPath = nil
tableView.beginUpdates()
// Need to put some logic if you pull to top it has to be + 1
tableView.deleteRowsAtIndexPaths([NSIndexPath(forRow: lastIndexPath.row - 1, inSection: 0)], withRowAnimation: .Fade)
tableView.endUpdates()
}
})
}
func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
return .None
}
func tableView(tableView: UITableView, shouldIndentWhileEditingRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
func tableView(tableView: UITableView, targetIndexPathForMoveFromRowAtIndexPath sourceIndexPath: NSIndexPath,
toProposedIndexPath proposedDestinationIndexPath: NSIndexPath) -> NSIndexPath {
if let lastIndexPath = self.lastIndicatorRowIndexPath {
print("Target indexpath indexpath to delete row \(lastIndexPath.section) row \(lastIndexPath.row)")
self.isIndicatorRowAddedInSection = false
tableView.beginUpdates()
tableView.deleteRowsAtIndexPaths([lastIndexPath], withRowAnimation: .None)
tableView.endUpdates()
self.lastIndicatorRowIndexPath = nil
}
self.isIndicatorRowAddedInSection = true
self.lastIndicatorRowIndexPath = proposedDestinationIndexPath
tableView.beginUpdates()
print("Indicator view inserted at section \(proposedDestinationIndexPath.section) row \(proposedDestinationIndexPath.row)")
tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: proposedDestinationIndexPath.row, inSection: proposedDestinationIndexPath.section)], withRowAnimation: .Automatic)
tableView.endUpdates()
return proposedDestinationIndexPath
}
}
extension ViewController: UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if self.isIndicatorRowAddedInSection {
return self.data.count + 1
}
return self.data.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if let indicatorIndexPath = self.lastIndicatorRowIndexPath where isIndicatorRowAddedInSection {
if indicatorIndexPath.section == indexPath.section && indicatorIndexPath.row == indexPath.row {
let cell = tableView.dequeueReusableCellWithIdentifier("Indicator", forIndexPath: indexPath)
cell.textLabel?.text = "IndicatorView: ROW \(indexPath.row) SECTION = \(indexPath.section)"
print("Indictorview cell for row")
return cell
}
}
let cell = tableView.dequeueReusableCellWithIdentifier("Default", forIndexPath: indexPath)
cell.textLabel?.text = "ROW = \(indexPath.row) SECTION = \(indexPath.section)"
return cell
}
}
I get this error when I actually run the code (this line is the problem var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(CellId) as UITableViewCell. THis is in a UITableViewController class.
import UIKit
class AlarmsTableViewController: UITableViewController {
var myData:Array<AnyObject> = []
override func viewDidLoad() {
myData = ["one", "two", "three", "four"]
}
override func didReceiveMemoryWarning() {
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myData.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let CellId:String = "Cell"
var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(CellId) as UITableViewCell
//if let ip = indexPath {
cell.textLabel?.text = myData[indexPath.row] as? String
//}
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
//Delete row from data source
//if let tv = tableView? {
myData.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
}
}
}
In the interface builder, select the TableViewController with which you are working with. Then, select the prototype cell and set its style to "Basic". Finally, set the cells reuse identifier to Cell.
I have a login screen - after login, I am displaying list in a table view with check boxes. After submitting button. all the selected check box labels should send to server. Login screen and displaying table working how to write action for submit import UIKit
class ViewController: UIViewController,UITableViewDataSource, UITableViewDelegate {
private let dwarves = [
"Sleepy", "Sneezy", "Bashful", "Happy",
"Doc", "Grumpy", "Dopey",
"Thorin", "Dorin", "Nori", "Ori",
"Balin", "Dwalin", "Fili", "Kili",
"Oin", "Gloin", "Bifur", "Bofur",
"Bombur"]
let simpleTableIdentifier = "SimpleTableIdentifier"
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return dwarves.count
}
func tableView(tableView: UITableView,
cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier(
simpleTableIdentifier) as? UITableViewCell
if (cell == nil) {
cell = UITableViewCell(
style: UITableViewCellStyle.Default, reuseIdentifier: simpleTableIdentifier)
}
let image = UIImage(named: "unchecked")
cell!.imageView.image = image
let highlightedImage = UIImage(named: "checked")
cell!.imageView.highlightedImage = highlightedImage
cell!.textLabel.text = dwarves[indexPath.row]
return cell!
}
/*func tableView(tableView: UITableView,
didSelectRowAtIndexPath indexPath: NSIndexPath) {
let rowValue = dwarves[indexPath.row]
for element in rowValue {
sel = [rowValue]
println(element)
}
}*/
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
let rowValue = dwarves[indexPath.row]; println("You selected cell \(indexPath.row)")
}
}
You can create an NSMutableArray instance variable to hold the selected values:
var selected = NSMutableArray()
Then, in your didSelectRowAtIndexPath method, add to the array if the object does not exist or remove the object if it does exist.
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let rowValue = dwarves[indexPath.row]; println("You selected cell \(indexPath.row)")
// if the item exsits then remove it
if selected.containsObject(rowValue) {
selected.removeObject(rowValue)
} else { // else the item doesn't exist so add it
selected.addObject(rowValue)
}
println(selected)
}