繁体   English   中英

具有不同节的CheckBox UITableView

[英]CheckBox UITableView with Different Sections

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

使用带有已打开/关闭状态的选中/未选中背景图像的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
    }


}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM