gpt4 book ai didi

ios - 在 swift 2.2 中处理 Tableview 中的切换

转载 作者:行者123 更新时间:2023-11-29 11:57:01 24 4
gpt4 key购买 nike

我有一个屏幕如下图所示: enter image description here

如您所见,我使用自定义单元格上传了包含学生姓名的列表,我希望在单击保存按钮时将学生的状态保存在数组中,我第一次为所有学生初始化数组,当状态为启用开关然后单击单元格索引处的此值转换为 1 但是当单击操作发生在开关上时我无法做到这一点现在只有在单击单元格(行)时我才能做同样的事情更改开关的状态以更新数组,而无需单击表中的完整行

主视图代码:

 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)


}




}

单元格代码:

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) {
}

}

更新:

主视图 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)
}

单元格 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) {
}

}

最佳答案

有几种方法可以做到这一点:使用closuredelegate,但我更喜欢使用delegate

  1. 为您的 teacherAttendanceCell 单元格创建一个 delegate,就像这个答案 https://stackoverflow.com/a/25792213/2739795 中一样

  2. 让你teacherAttendanceVC符合delegate

  3. 每次 cellForRowAtIndexPath 调用时设置 cell.delegate = self。同时将单元格返回到您的委托(delegate)方法中

  4. 从委托(delegate)内部调用方法stateChanged

  5. 当委托(delegate)方法调用时,如果切换单元格,您可以获得索引

tableView.indexPathForCell(cellFromParam)

关于ios - 在 swift 2.2 中处理 Tableview 中的切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38644350/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com