Swift tableview 单元格单选按钮实现 [英] Swift tableview cell radio button implementation

查看:51
本文介绍了Swift tableview 单元格单选按钮实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 tableview 自定义单元格中放置一个单选按钮.每当用户单击 tableview 单元格或按钮时,单选按钮需要工作.我尝试使用下面的代码,但没有很好地执行.

I need to place a radio button in tableview custom cell. whenever user clicks the tableview cell or button then radio button needs to work. I tried by using below code but didn't execute well.

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 中创建单选按钮 -并且有 2 个很棒的很酷的提示!!

Here's a great solution for creating radio buttons in a UITableView using a storyboard that requires zero code - and has 2 great Cool Tips!!

  • 确保您的表格视图设置为单选,并使用静态单元格.

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

Add a Basic cell, set the image to be your unchecked button image, and make sure the selection style is Default

  • 酷提示#1:点击并选择单元格的图像视图,然后将其突出显示的图像设置为选中状态.当单元格被高亮或选中时,其中的图像视图将改变以显示其高亮状态.
  • Cool Tip # 1: Click on and select the cell's image view, and then set it's highlighted image to be your checked state. When the cell is highlighted or selected, the image view within will change to show its highlighted state.

  • 酷技巧#2: 接下来,将一个 UIView 拖到单元格的内容视图中,在文本标签后面.当您使用基本单元格时,您将无法将其直接放入单元格中,您需要将其拖入左侧的文档大纲中.然后将其连接到单元格的选定的背景视图出口.选择(或突出显示)单元格时,将显示在后台中的此视图.在本例中,我们将使用它来防止出现灰色背景,因此将其颜色设置为 Clear.请注意,视图的大小无关紧要,并且无需设置任何约束 - 它会在运行时自动调整大小以匹配单元格.
  • Cool Tip # 2: Next, drag a UIView into the cell's content view, behind the text label. As you're using a basic cell, you won't be able to drop it directly into the cell, you'll need to drag it into onto the Document Outline on the left instead. Then hook this up to the cell's selected background view outlet. When a cell is selected (or highlighted), this view will be displayed in the background. In this case, we're going to use it to prevent the grey background appearing, so set its colour to Clear. Note that it doesn't matter what size the view is, and there's no need to set any constraints - it's automatically sized to match the cell at runtime.

  • 最后,复制此单元格并更改每个单选按钮选项的文本.构建并运行,您将拥有无代码的单选按钮!

这篇关于Swift tableview 单元格单选按钮实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆