[英]Swift tableview cell radio button implementation
我需要在tableview自定义单元格中放置一个单选按钮。 每当用户单击表格视图单元格或按钮时,单选按钮都需要工作。 我尝试使用下面的代码,但执行效果不佳。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:TableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! TableViewCell
cell.country.text = self.animals[indexPath.row]
cell.selectionStyle = UITableViewCellSelectionStyle.none;
if selectedRows.contains(indexPath)
{
cell.radioButton.setImage(UIImage(named:"check.png"), for: .normal)
}
else
{
cell.radioButton.setImage(UIImage(named:"uncheck.png"), for: .normal)
}
return cell
}
这是一个很棒的解决方案,它使用需要零代码的情节UITableView
在UITableView
创建单选按钮-并具有2个很棒的酷提示!!
确保将表视图设置为“ 单选” ,并使用“ 静态”单元格 。
添加一个基本单元格,将图像设置为未选中的按钮图像,并确保选择样式为默认
UIView
拖到单元格的内容视图中的文本标签后面。 在使用基本单元格时,您将无法直接将其拖放到该单元格中,而需要将其拖动到左侧的Document Outline中。 然后将其连接到单元格的选定背景视图插座。 选择一个单元格(或突出显示一个单元格)时,此视图将在后台显示。 在这种情况下,我们将使用它来防止出现灰色背景,因此将其颜色设置为Clear 。 请注意,视图的大小无关紧要,并且无需设置任何约束-它会在运行时自动调整大小以匹配单元格。 在TableViewCell
类中,为什么不创建数据源元素并覆盖它的didSet
。 同样在您的UITableView
数据源中,我建议使用的数组不仅仅是String
。
我还没有编译下面的内容,所以这只是一个想法。
import UIKit
class TableViewCell : UITableViewCell {
var data: Animal? {
didSet {
self.country.text = data.description
if (data.isSelected) {
self.radioButton.setImage(UIImage(named:"check.png"), for: .normal)
} else {
self.radioButton.setImage(UIImage(named:"uncheck.png"), for: .normal)
}
}
}
}
当然,在视图控制器中,每当点击一行时,您都必须设置isSelected
属性。
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
var animal = self.animals[indexPath.row]
animal.isSelected = !animal.isSelected
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:TableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! TableViewCell
cell.data = self.animals[indexPath.row]
}
对于您的Animal
可能是这样的:
struct Animal {
var description: String
var isSelected: Bool
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.