我想在我的“表格视图”单元格中添加复选标记。我想只是cell.accessoryType = UITableViewCellAccessoryCheckmark
在我的didSelectRowAt
方法中实现,但是在使用自定义UITableViewCell
子类时却无法使它正常工作。
自定义单元:
class TableCell: UITableViewCell {
@IBOutlet weak var tableLabel: UILabel!
var arrayOneToDisplay:ArrayOne?
let arrayOne = ArrayOne()
func displayTable(_ currentArrayOne:ArrayOne) {
// Keep a reference to the cell
arrayOneToDisplay = currentArrayOne
// Get the Table Cells data
var tableCell = arrayOne.tableCells
// Set the instructionLabel
tableLabel.text = currentArrayOne.tableCells![0]
}
ViewController:
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Make sure the array contains at least 1 item
guard arrayOne.count > 0 else {
return 0
}
// Return the number of items for this array
let currentArrayOne = arrayOne[currentArrayOneIndex!]
if currentArrayOne.tableCells != nil {
return currentArrayOne.tableCells!.count
}
else {
return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Get a cell
let cell = tableView.dequeueReusableCell(withIdentifier: "TableCell", for: indexPath) as! TableCell
// Get the instruction that the tableView is asking about
let tableLabel = cell.tableLabel
if tableLabel != nil {
let currentArrayOne = arrayOne[currentArrayOneIndex!]
if currentArrayOne.tableCells != nil && indexPath.row < currentArrayOne.tableCells!.count {
// Set the text for the label
tableLabel!.text = currentArrayOne.tableCells![indexPath.row]
}
}
// Return the cell
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
}
当我尝试cell.accessoryType
在ViewController中实现时,Xcode无法识别accessoryType
。我相信这是因为我的方法是针对UITableView
而非方法的UITableViewCell
,因此使用自定义单元格的额外皱纹给我带来了一些困惑。任何指导,不胜感激!
您应该accessoryType
在cellForRowAt
方法中进行设置,尝试将其重写为:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "TableCell", for: indexPath) as! TableCell
cell.accessoryType = .checkmark
guard let arrayOneIndex = currentArrayOneIndex, arrayOneIndex < arrayOne.count else { return cell }
let currentArrayOne = arrayOne[arrayOneIndex]
guard let tableCells = currentArrayOne.tableCells, indexPath.row < tableCells.count else { return cell }
cell.tableLabel.text = tableCells[indexPath.row]
return cell
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句