2017-06-06 52 views
0

尝试创建一个UITableview与包含不同部分的复选框按钮,我如何设法为新节中的每个按钮分配一个唯一的标记。由于indexpath.row将在每一个新的部分被重复,不能使用indexpath.row复选框与不同部分的UITableView

+1

这是原因之一**不要**使用标签来标识行。相反,您应该在“选中该复选框”时更新数据源。这样,只要tableview重新加载该单元格(例如滚动后),就可以控制复选框的状态。 – DonMag

+0

下面是一个简单的例子 - 它使用“UISwitch”而不是“复选框”......但它将几乎完全相同:https://stackoverflow.com/questions/44369289/swift-3-uiswitch-in-tableviewcell - 失去状态当滚动/ 44370083#44370083 – DonMag

+0

我有UIButton,UISwitch确实有sender.isOn属性,但只是一个UIButton与背景图像变化 – Max

回答

0

实施例使用具有选中/取消背景图像的UIButton具有开/关状态:

// 
// TableWithCheckTableViewController.swift 
// SWTemp2 
// 
// Created by Don Mag on 6/6/17. 
// Copyright © 2017 DonMag. All rights reserved. 
// 

import UIKit 


class MyCheckTableViewCell: UITableViewCell { 
    @IBOutlet weak var myLabel: UILabel! 
    @IBOutlet weak var myCheckButton: UIButton! 

    var checkedImage = UIImage(named: "Checked") 
    var unCheckedImage = UIImage(named: "UnChecked") 

    var isOn: Bool = false { 
     didSet { 
      myCheckButton.setBackgroundImage(self.isOn ? checkedImage : unCheckedImage, for: .normal) 
     } 
    } 

    var checkTapAction : ((Bool)->Void)? 

    @IBAction func buttonTapped(_ sender: Any) { 

     self.isOn = !self.isOn 

     checkTapAction?(self.isOn) 
    } 


} 

// simple data object 
class MyCheckObject: NSObject { 
    var theTitle = "" 
    var theCheckState = false 

    init(_ title: String) { 
     theTitle = title 
    } 
} 

class TableWithCheckTableViewController: UITableViewController { 

    // array of MyObjects 
    var myData = [MyCheckObject]() 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     // just to make it a little easier to see the rows scroll 
     tableView.rowHeight = 60 

     // create 40 data objects for the table 
     for i in 1...40 { 
      let d = MyCheckObject("Data Item: \(i)") 
      myData.append(d) 
     } 

     tableView.reloadData() 

    } 

    // MARK: - Table view data source 
    override func numberOfSections(in tableView: UITableView) -> Int { 
     return 1 
    } 

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return myData.count 
    } 

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "MyCheckTableViewCell", for: indexPath) as! MyCheckTableViewCell 

     // Configure the cell... 
     let d = myData[indexPath.row] 
     cell.myLabel.text = d.theTitle 
     cell.isOn = d.theCheckState 

     // set a "Callback Closure" in the cell 
     cell.checkTapAction = { 
      (isOn) in 
      // update our Data Array to the new state of the switch in the cell 
      self.myData[indexPath.row].theCheckState = isOn 
     } 

     return cell 
    } 


} 
+0

完美!令人惊讶的是如何工作,没有更多的设置独特的标签和不需要的代码 – Max