2017-10-20 54 views
1

我在包含开关的Swift 4项目中创建了一个自定义单元格。当我选择任何开关时,我选择表格中的第10个开关。表格中有34个单元格。我尝试了许多不同的用户交互启用/禁用组合。即使未选定开关的状态显示为“开”,相关的动作也不会触发。下面是激发动作的代码:开关状态时,UISwitch在表格中选择多个单元格

@IBAction func SwitchAction(_ sender: UISwitch) { 

    let switchPosition = sender.convert(CGPoint(), to:tableView) 
    let indexPath = tableView.indexPathForRow(at:switchPosition) 
    let ipath = indexPath?.row 
} 

override func numberOfSections(in tableView: UITableView) -> Int { 
    return 1 
} 

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 

    return taskList.count 

} 
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 
    return 75 
} 

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    //let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "Cell") 
    let cell: customTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! customTableViewCell 
    cell.LabelSelect.text=taskList[indexPath.row] 

    return cell 
} 
+0

欢迎来到堆栈溢出 - 很高兴有你。请阅读我如何提出一个好问题? https://stackoverflow.com/help/how-to-ask以及如何创建一个最小化,完整和可验证的示例,以帮助将堆栈溢出内容保持在最高级别,并增加获得正确答案的机会。 https://stackoverflow.com/help/mcve – 2017-10-20 01:41:37

+0

你的开关动作是否给你正确的索引? – Tj3n

+0

在cellforrowatindexpath方法中添加切换目标 – Vinodh

回答

0

这是由于单元被重新使用。当你滚动tableView时,一些行将离开屏幕;关联的单元格被放入队列中。其他行出现在屏幕上;调用cellForRowAt方法并从队列中取出一个单元(因此为dequeueReusableCell),以用于新行。如果当单元格离开屏幕时开关处于打开状态,即使它现在与一个完全不同的行相关,它仍然会在屏幕上显示。

解决方案是维护一个数组,指示给定行的开关是打开还是关闭。然后,您可以使用该阵列在cellForRowAt方法中正确设置打开或关闭开关。

+0

这是完全有道理的。谢谢! –

相关问题