UITableView 和 UIButtons 中的多个部分 swift [英] Multiple sections in UITableView and UIButtons swift
问题描述
我有一个 UITableView 有部分(Category0,Category1,..),并且特定部分的每一行都是一个 UITableView,其中有一个部分是问题(Question1,..)和行是选项被回答(选项 1,选项 2,...).问题是当我单击特定类别中的按钮和特定问题(类别 0、问题 1、选项 0)时,请参阅屏幕截图 1,
I have a UITableView that has sections (Category0, Category1,..), and every row of a specific section is a UITableView that has one section which is the question (Question1,..) and rows which are the options to be answered (option1, option2,..). The problem is when I click on a button in a specific category and a specific question (Category0, question1, option0) see screenshot1,
立即点击另一个类别中的另一个按钮(类别1,问题2,选项0)见截图2,
immediately another buttons in another categories are clicked (Category1, question2, option0) see screenshot2,
和(类别 4,问题 1,选项 0)见截图 3.
and (Category4, question1, option0) see screenshot3.
代码如下:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? insideTableViewCell
cell?.answerlabel.text = "option \(indexPath.row)"
cell?.initCellItem(id: (myObject?.id)! , answer: (myObject?.answerArray![indexPath.row] as? String)!)
return cell!
}
在TableViewCell里面的自定义UITableViewCell中:
In a custom UITableViewCell which is insideTableViewCell:
func initCellItem(id: Int , answer: String) {
radioButton.setImage( imageLiteral(resourceName: "unchecked"), for: .normal)
radioButton.setImage( imageLiteral(resourceName: "checked"), for: .selected)
radioButton.tag = id
radioButton.setTitle(answer, for: UIControlState.disabled)
radioButton.addTarget(self, action: #selector(self.radioButtonTapped), for: .touchUpInside)
}
@objc func radioButtonTapped(_ radioButton: UIButton) {
print(radioButton.tag)
print(radioButton.title(for: UIControlState.disabled) as Any)
let answer = radioButton.title(for: UIControlState.disabled) as Any
let StrId = String(radioButton.tag)
defaults.set(answer, forKey: StrId)
let isSelected = !self.radioButton.isSelected
self.radioButton.isSelected = isSelected
if isSelected {
deselectOtherButton()
}
}
func deselectOtherButton() {
let tableView = self.superview as! UITableView
let tappedCellIndexPath = tableView.indexPath(for: self)!
let section = tappedCellIndexPath.section
let rowCounts = tableView.numberOfRows(inSection: section)
for row in 0..<rowCounts {
if row != tappedCellIndexPath.row {
let cell = tableView.cellForRow(at: IndexPath(row: row, section: section)) as! insideTableViewCell
cell.radioButton.isSelected = false
}
}
}
推荐答案
我认为有一些简单的代码可以帮助您:- 如果它不适合您,请不要介意 :-
There has some and simple code I think it will help you :- if it is not sutable for you pls don't mind :-
if (!btnGreen3.isSelected)
{
btnGreen3.isSelected = !btnGreen3.isSelected
}
btnBlue3.isSelected = false
btnBlack3.isSelected = false
这篇关于UITableView 和 UIButtons 中的多个部分 swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!