Reputation: 1
I've created a table that has cells with text on the left and a UISwitch on the right. The table is linked to an array with about 70 different strings (and therefore has 70 cells in this table). I have also created an empty array that I want to store strings in. My question is: how do I add strings to the empty array using the UISwitch? I can't seem to figure out how to reference the cells in my table and add whatever text is inside the cell to my empty array only using the UISwitch.
''' func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let utilities = Utilities()
return utilities.allFactions.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let utilities = Utilities()
// Writes a new faction on every line of the table
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = utilities.allFactions[indexPath.row]
// Creates a switch that can be toggle "on" or "off"
let mySwitch = UISwitch()
mySwitch.addTarget(self, action: #selector(didChangeSwitch(_:)), for: .valueChanged)
mySwitch.isOn = false
// Adds the switch to the right side of the cell
cell.accessoryView = mySwitch
return cell
}
'''
Upvotes: 0
Views: 225
Reputation: 331
This should help you starting it. You should do some more checking like if the string exist on the new array or not.
// This is your datasource, your array that provides data to the tableview.
let stringSource = ["String 1", "String 2", "String 3", "String 4"]
// Initialise a new string array
var newStringArray = Array<String>()
Below is the normal datasource method for the tableview
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return stringSource.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
cell.textLabel?.text = stringSource[indexPath.row]
let mySwitch = UISwitch()
// Assign the index row of the cell to the tag - this ensure that the switch has a unique value to it (an ID if you may).
mySwitch.tag = indexPath.row
mySwitch.addTarget(self, action: #selector(didChangeSwitch(_:)), for: .valueChanged)
mySwitch.isOn = false
cell.accessoryView = mySwitch
return cell
}
and the selector method:
@objc func didChangeSwitch(_ sender: UISwitch) {
// Since we know where the switch comes from (via the tag property) we can
// simply access the value and append it to our new one
newStringArray.append(stringSource[sender.tag])
print(newStringArray)
}
Upvotes: 1