如何允许用户仅打开以编程方式构建的单个 uiSwitch 并存储交换机的数据



car register tableview中有一个以编程方式构建的uiswitch,当用户为他们选择的汽车打开它时,布尔值被保存并存储在核心数据中,汽车品牌将显示在不同的视图控制器中。

问题: 如何使用户只能打开一个开关,以及如何在开关打开时保存该数据(汽车名称(?

法典:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellS = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableViewCell
//here is programatically switch make to the table view
switchView.setOn(false, animated: true)
switchView.tag = indexPath.row // for detect which row switch Changed
//        switchView.addTarget(self, action: #selector(self.switchChanged(_:)), for: .valueChanged)
cellS.accessoryView = switchView
if indexPath.row != 0 {
switchView.isEnabled = true
UserDefaults.standard.set(switchView.isOn, forKey: "CarSwitch")

这是我尝试的代码:

if switchView.isSelected {
UserDefaults.standard.set(indexPath.row, forKey: "usethiscar")
}
}
if tableView == table1 {
let cell = table1.dequeueReusableCell(withIdentifier: "Cell")
let row = indexPath.row
cell?.textLabel?.text = table1Data[row]
return cell!
}
return UITableViewCell()
} 

这就是它的样子

这是按下"添加汽车"的时候

当两个开关打开时

,不应发生这种情况

我以前实现过这样的任务。 这个想法是保留对当前所选索引的引用和 当用户切换汽车时,使用它来转动选定的开关off

下面的代码未经测试。请使用它们作为参考

// the table data model
var carNames: [String] = []
// this will hold the current selected tag index
var selectedTagIndex: Int = -1
// configuring the cell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
{
// copied from your code.
// NOTE: You might wan't to create a custom cell for this
// to access the switch view directly when turning it off
// during the car selection
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableViewCell
// switch on if the index path row is equal to the current
// selected index, switch off otherwise
cell.switchView.isOn = (indexPath.row == self.selectedTagIndex)
// set the tag index
cell.switchView.tag = indexPath.row
}
// Switch change-in-value handler
func onCarSwitchValueChanged(sender: UISwitch)
{
guard sender.isOn else 
{
// if switch is off
// remove selected tag index
self.selectedTagIndex = -1
// don't execute the code below
return 
}
// the tag tag index of the switch
let switchIndexTag =  sender.tag
// check if there is a previously selected switch 
guard self.selectedTagIndex != -1  else
{
// if none, just save the selected tag index
self.selectedTagIndex = switchIndexTag
// don't execute the code below
return 
}
// OPTION 1: Turn off the selected switch manually.
// Create a custom cell to be able to access the 
// the switch view directly
// create index path using the tag index
let indexPath = IndexPath(row: switchIndexTag, section: 0)
let cell = tableView.cellForRow(at: indexPath!) as! TheCustomCellClass
cell.switchView.isOn = false 
// save the current selected switch tag index
self.selectedTagIndex = switchView.tag
// OPTION 2: Reload the entire table 
// self.tableView.reloadData()  
}

最新更新