我正在用 swift 4 做项目。我在 tableview cell
中创建了 radiobutton
类。单击哪个 radio button
时,我想获取 cell index
。请帮助我。
编辑:我刚刚添加了我的整个代码。我无法解决我的问题。所有的代码如下。我创建了一个单选按钮类并给它一个单选按钮功能。我尝试将单选按钮集成到 TableView 中,并在单击按钮时获取单元格的索引,如下所示,但它给出了 libc++abi.dylib: terminating with uncaught exception of type NSException 错误。
import UIKit
class TVCIsGuvenligi: UITableViewCell {
lazy var radioButtonGroup: [RadioButton] = {
return [
btnRadioEvet,
btnRadioHayir,
]
}()
@IBOutlet var lblSoru: UILabel!
@IBOutlet var lblSoruAyrinti: UILabel!
@IBOutlet var lblEvet: UILabel!
@IBOutlet var lblHayır: UILabel!
@IBOutlet var btnRadioEvet: RadioButton!
@IBAction func btnRadioEvet(_ sender: RadioButton)
{
let indexPath = IndexPath.init(row: sender.tag, section: 0)
updateRadioButton(sender)
print("index \(indexPath)")
}
@IBOutlet var btnRadioHayir: RadioButton!
@IBAction func btnRadioHayir(_ sender: RadioButton)
{
let indexPath = IndexPath.init(row: sender.tag, section: 0)
updateRadioButton(sender)
print("index \(indexPath)")
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func updateRadioButton(_ sender: RadioButton){
radioButtonGroup.forEach { $0.isSelected = false }
sender.isSelected = !sender.isSelected
}
}
ViewController.swift
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellIs", for: indexPath) as! TVCIsGuvenligi
cell.lblSoru.text = myTitle[indexPath.row]
cell.lblSoruAyrinti.text = myTitle[indexPath.row]
cell.btnRadioEvet.tag = (indexPath.row)
cell.btnRadioEvet.addTarget(self, action: #selector(getter: cell.btnRadioEvet), for: UIControlEvents.touchUpInside)
print("current cell tag \(cell.btnRadioEvet.tag)")
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//getting the index path of selected row
let indexPath = tableView.indexPathForSelectedRow
//getting the current cell from the index path
let currentCell = tableView.cellForRow(at: indexPath!)! as! TVCIsGuvenligi
//getting the text of that cell.
let currentItem = currentCell.lblSoru.text
print("current item \(currentItem)")
}
最佳答案
使用,
currentCell.radioButton.tag = indexPath.row
并使用这个标签获取单选按钮点击的索引
关于ios - 单击swift 4中的单选按钮时如何获取 TableView 索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50508663/