簡體   English   中英

觸摸單元格時如何調用復選框按鈕的動作?

[英]How can I call the action of a checkbox button when the cell is touched?

我正在使用包含標簽和按鈕的自定義單元格。 在我的按鈕中,有一個與之關聯的動作,即,當觸摸按鈕時,按鈕會更改其圖像並更改為選中的圖像。 但是我希望在觸摸整個單元格時調用該動作。

extension HostOptionViewController: UITableViewDataSource, UITableViewDelegate{

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let question = Question[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: "QuestionOptionCell") as! ViewCellTableViewCell
        cell.setText(option: question)
        arrayOfCells.append(cell)
        return cell
    }

在我的自定義單元中

import UIKit

class ViewCellTableViewCell: UITableViewCell {
    @IBOutlet weak var DataCell: UILabel!
    @IBOutlet weak var checkBox: UIButton!

    @IBAction func CheckBoxFunc(_ sender: Any) {
        if checkBox.isSelected{
            checkBox.isSelected = false
        }
        else{
            checkBox.isSelected = true
        }
    }

    func setText(option: Data){
        DataCell.text = option.data
    }
}

我想在觸摸單元格時調用“ CheckBoxFunc”。

按鈕的動作。

如果要在選擇單元格時調用CheckBoxFunc ,則應在didSelectRowAtIndexPath中調用它,例如:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    // Get your Custom cell here using dequeueReusableCell
    // Call the CheckBoxFunc
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let selectedCell: ViewCellTableViewCell = tableView.cellForRow(at: indexPath)! as! ViewCellTableViewCell
    selectedCell.checkBox.addTarget(self, action: #selector(TableViewController.checkBoxTapped(_:)), for: .touchUpInside)
}

func checkBoxTapped(sender:UIButton) {
    let question = Question[sender.tag]
    print(question)
}

不要忘記在cellForRowIndex方法中為復選框按鈕添加標簽。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM