1

I have one screen like the following picture: enter image description here

I uploaded list with student name by using custom cell as you are seeing and I want when click on save button save the status of student in array , I initialized array with 0 for all student at the first time and when the status of switch is enabled then this value at the clicked cell index converted to 1 but I couldn't make that when the click action happened on switch this is only now happening when click on the cell ( row ) how I can do the same thing when only change the status of switch to update the array without click on complete row at table

Code of main view :

 import UIKit

 class teacherAttendanceVC: UIViewController , UITableViewDataSource,UITableViewDelegate  {



@IBOutlet weak var studentlistTable: UITableView!

@IBOutlet weak var loadIndicator: UIActivityIndicatorView!


var username:String?
var classID: String?
var branchID: String?

var normal_id = [String]()
var student_name = [String]()

 var student_attendance = [String]()





//Sent Data
var n_id = ""
var stu_name = ""



@IBAction func backButton(sender: AnyObject) {

    self.dismissViewControllerAnimated(true, completion: nil )

}

override func viewDidLoad() {
    super.viewDidLoad()

    studentlistTable.delegate = self
    studentlistTable.dataSource = self


    let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
    username = prefs.objectForKey("user")as! String
    classID = prefs.objectForKey("ClassID")as! String
    branchID = prefs.objectForKey("BranchID")as! String




    self.loadIndicator.startAnimating()

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in



        self.loadList()


        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            self.loadIndicator.stopAnimating()
            self.studentlistTable.reloadData()


        })
    });


}


override func viewDidAppear(animated: Bool) {

}


func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return normal_id.count
}


func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    //This method to define each cell at Table View

    let cell = self.studentlistTable.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! teacherAttendanceCell



    cell.studentNameLabel.text = student_name[indexPath.row]


    return cell
}


func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    // Get Cell Label
    let currentCell = studentlistTable.cellForRowAtIndexPath(indexPath) as! teacherAttendanceCell!

    student_attendance[indexPath.row] = currentCell.status


}





@IBAction func saveButton(sender: AnyObject) {
    print(student_attendance) // this only to ensure from the final array before sending to server 
}


func loadList()
{
    var normallink = "myurl"
    normallink = normallink + "?classid=" + self.classID! + "&branchid=" + self.branchID!

    print(normallink)

    var studentParentURL:NSURL = NSURL (string: normallink)!
    let data = NSData(contentsOfURL: studentParentURL)!



    do {
        let json = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)

        if let alldata = json["data"] as? [[String: AnyObject]] {
            for onedata in alldata {
                if let no_id = onedata["id"] as? String {
                    normal_id.append(no_id)
                }
                if let s_name = onedata["studentName"] as? String {
                    student_name.append(s_name)
                }




            }
        }
    } catch {
        print("Error Serializing JSON: \(error)")
    }

    if(normal_id.count != 0)
    {
        for i in 1...self.normal_id.count
        {
            self.student_attendance.append("0")
        }
    }




    print(normal_id.count)
    print(student_name.count)


}




}

Cell Code :

class teacherAttendanceCell: UITableViewCell {

@IBOutlet weak var studentNameLabel: UILabel!
@IBOutlet weak var attendSwitch: UISwitch!

var status:String = ""

override func awakeFromNib() {
    super.awakeFromNib()

    if(attendSwitch.on)
    {
        status = "1"
        print("ON")
    }
    else{
        status = "0"
        print("OFF")

    }

    attendSwitch.addTarget(self, action: "stateChanged:", forControlEvents: UIControlEvents.ValueChanged)

}


func stateChanged(switchState: UISwitch) {
    if switchState.on {
        status = "1"
        print("ON")
    } else {
       status = "0"
        print("OFF")
    }
}

override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
}

@IBAction func attendSwitchChanged(sender: AnyObject) {
}

}

Updated:

Main View Controller:

import UIKit

class teacherAttendanceVC: UIViewController , UITableViewDataSource,UITableViewDelegate,CellInfoDelegate  {



@IBOutlet weak var studentlistTable: UITableView!

@IBOutlet weak var loadIndicator: UIActivityIndicatorView!


var username:String?
var classID: String?
var branchID: String?

var normal_id = [String]()
var student_name = [String]()

 var student_attendance = [String]()





//Sent Data
var n_id = ""
var stu_name = ""



@IBAction func backButton(sender: AnyObject) {

    self.dismissViewControllerAnimated(true, completion: nil )

}

override func viewDidLoad() {
    super.viewDidLoad()

    studentlistTable.delegate = self
    studentlistTable.dataSource = self


    let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
    username = prefs.objectForKey("user")as! String
    classID = prefs.objectForKey("ClassID")as! String
    branchID = prefs.objectForKey("BranchID")as! String





    self.loadIndicator.startAnimating()

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in



        self.loadList()



        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            self.loadIndicator.stopAnimating()
            self.studentlistTable.reloadData()


        })
    });


}


override func viewDidAppear(animated: Bool) {

}


func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return normal_id.count
}


func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    //This method to define each cell at Table View

    let cell = self.studentlistTable.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! teacherAttendanceCell
     cell.delegate = self




    cell.studentNameLabel.text = student_name[indexPath.row]
     student_attendance[indexPath.row] = cell.status


    //print(student_attendance.count)
    //let currentCell = studentlistTable.cellForRowAtIndexPath(indexPath) as! teacherAttendanceCell!
    // student_attendance.append(cell.status)

    return cell
}


func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    // Get Cell Label
  //  let currentCell = studentlistTable.cellForRowAtIndexPath(indexPath) as! teacherAttendanceCell!

   // student_attendance[indexPath.row] = currentCell.status
    //print("OK Status here!" + String(student_attendance.count))

}





@IBAction func saveButton(sender: AnyObject) {
    print(student_attendance)
}


func loadList()
{
    var normallink = "mylinkhere"
    normallink = normallink + "?classid=" + self.classID! + "&branchid=" + self.branchID!

    print(normallink)

    var studentParentURL:NSURL = NSURL (string: normallink)!
    let data = NSData(contentsOfURL: studentParentURL)!


    do {
        let json = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)

        if let alldata = json["data"] as? [[String: AnyObject]] {
            for onedata in alldata {
                if let no_id = onedata["id"] as? String {
                    normal_id.append(no_id)
                }
                if let s_name = onedata["studentName"] as? String {
                    student_name.append(s_name)
                }




            }
        }
    } catch {
        print("Error Serializing JSON: \(error)")
    }

    if(normal_id.count != 0)
    {
        for i in 1...self.normal_id.count
        {
            self.student_attendance.append("0")
        }
    }




    print(normal_id.count)
    print(student_name.count)

}


func processThatNumber(theStatus: String) {
    print("out : \(theStatus)")

}

}

protocol CellInfoDelegate {
func processThatNumber(theStatus: String)
 }

Cell View Controller:

import UIKit

class teacherAttendanceCell: UITableViewCell{

@IBOutlet weak var studentNameLabel: UILabel!
@IBOutlet weak var attendSwitch: UISwitch!

var status:String = ""
var delegate: CellInfoDelegate?

override func awakeFromNib() {
    super.awakeFromNib()

    if(attendSwitch.on)
    {
        status = "1"
        print("ON")
    }
    else{
        status = "0"
        print("OFF")

    }

    attendSwitch.addTarget(self, action: "stateChanged:", forControlEvents: UIControlEvents.ValueChanged)

}


func stateChanged(switchState: UISwitch) {
    if switchState.on {
        status = "1"
        print("ON")
    } else {
       status = "0"
        print("OFF")
    }

    if let delegate = self.delegate {
        delegate.processThatNumber(self.status)
    }
}

override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
}

@IBAction func attendSwitchChanged(sender: AnyObject) {
}

}
Samah Ahmed
  • 419
  • 8
  • 24

1 Answers1

1

There are few ways to do this: using closure or delegate, but I preferred to use delegate.

  1. Create a delegate for your teacherAttendanceCell cell like in this answer https://stackoverflow.com/a/25792213/2739795

  2. Make you teacherAttendanceVC conforms the delegate

  3. Each time when cellForRowAtIndexPath calls set cell.delegate = self. Also return the cell into your delegate method

  4. Call method from delegate insidestateChanged

  5. And when delegate method calls you can get an index if switched cell

tableView.indexPathForCell(cellFromParam)
Community
  • 1
  • 1
Andrew Bogaevskyi
  • 2,251
  • 21
  • 25
  • I updated my post , I'm not familiar a lot with using of protocol in IOS , but until now when I'm clicking on save button I got the same old array with zeros of all items but when I'm switching switch I can print status value from main view controller through protocol but I don't know how and where I can get the index of cell to change the value for this item at array in main view controller – Samah Ahmed Jul 29 '16 at 21:38
  • I solved my problem as you said before and depends on this post to take practical steps because as I mentioned I didn't deal with protocol before that http://stackoverflow.com/questions/29913066/how-to-access-the-content-of-a-custom-cell-in-swift-using-button-tag – Samah Ahmed Jul 30 '16 at 13:48