我创建了一个表格,左边是有文本的单元格,右边是一个UISwitch。该表链接到一个大约有70个不同字符串的数组(因此在这个表中有70个单元格)。我还创建了一个空数组,我想在其中存储字符串。我的问题是:如何使用UISwitch向空数组中添加字符串?我似乎不知道如何引用表中的单元格,并仅使用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
}
'''
这应该能帮助你启动它。你应该做一些更多的检查,比如字符串是否存在于新的数组中。
// 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>()
下面是正常的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
}
和选择器方法。
@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)
}