I have an array called teamArray which contain a teamObject with a id, name and shortname. these names is looped into and populated in an tableView. All these cells can be selected and when a cell is selected the indexPath is inserted into a cellSelected array. I would like to save the selected cells id's from the teamArray into a new array. So I guess I need to compare the cellSelected arrays indexPath with the teamArray? How can I do this?
arrays
var teamArray = Array<Team>()
var cellSelected = NSMutableArray()
didSelectRowAtIndexPath
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
if (self.cellSelected.containsObject(indexPath)) {
self.cellSelected.removeObject(indexPath)
} else {
self.cellSelected.addObject(indexPath)
}
tableView.reloadData()
}
teamObject
class Team: NSObject{
var id: Int!
var name: NSString!
var shortname: NSString!
init(id: Int, name:NSString, shortname: NSString) {
self.id = id
self.name = name
self.shortname = shortname
}
}
var teamSelected = [Team]()
In your didSelectRowAtIndexPath
function:
let team = self.teamArray[indexPath.row] as Team
var removed = false
for (index, value) in enumerate(self.teamSelected) {
if (value == team) {
self.teamSelected.removeAtIndex(index)
removed = true
}
}
if (!removed) {
self.teamSelected.append(team)
}
in your cellForRowAtIndexPath
function:
let team = self.teamArray[indexPath.row] as Team
var removed = false
for (index, value) in enumerate(self.teamSelected) {
if (value == team) {
cell.accessoryView = cell.accessoryCheck
removed = true
}
}
if (!removed) {
cell.accessoryView = cell.accessoryUncheck
}
You can then loop through teamSelected
when you want to access the ID of the selected Team
's
EDIT: Changed name of cellSelected
to teamSelected
Your main teamArray
, which is load in TableView
var teamArray = ["Kirit Modi","Kirit Modi 1","Kirit Modi 2","Kirit Modi 3","Kirit Modi 4","Kirit Modi 5","Kirit Modi 6","Kirit Modi 7","Kirit Modi 8","Kirit Modi 9"]
And cellSelected
,
var cellSelected = : [String] = []
In TableView
delegate didSelectRowAtIndexPath
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
if contains(cellSelected, Name[indexPath.row])
{
cellSelected.removeObject(Name[indexPath.row])
}
else{
cellSelected.append(Name[indexPath.row])
}
}
Use the below function to remove object from Array.
extension Array {
mutating func removeObject<U: Equatable>(object: U) {
var index: Int?
for (idx, objectToCompare) in enumerate(self) {
if let to = objectToCompare as? U {
if object == to {
index = idx
}
}
}
if(index != nil) {
self.removeAtIndex(index!)
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.