2017-10-20 51 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

這是完全有道理的。謝謝! –

相關問題