尝试使用包含不同部分的复选框按钮创建UITableview,如何设置为新部分中的每个按钮分配唯一标记。由于indexpath.row将在每个新节中重复,因此Cant使用indexpath.row
答案 0 :(得分: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
}
}