繁体   English   中英

Swift Tableview Cell单选按钮实现

[英]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
    }

这是一个很棒的解决方案,它使用需要代码的情节UITableViewUITableView创建单选按钮-并具有2个很棒的酷提示!!

  • 确保将表视图设置为“ 单选” ,并使用“ 静态”单元格

  • 添加一个基本单元格,将图像设置为未选中的按钮图像,并确保选择样式为默认

在此处输入图片说明

  • 酷提示#1:单击并选择单元格的图像视图,然后将其突出显示的图像设置为选中状态。 突出显示或选择单元格后,其中的图像视图将更改以显示其突出显示的状态。

在此处输入图片说明

  • 酷提示#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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM