xcode Swift - 为 tableView 中的每个单元格添加一个复选框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33322321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swift - Adding a checkbox to every cell in the tableView
提问by NABS
I've already made a table view which allows the user to add tasks to the table view, but now I need to add a checkbox in front of each task, so that the user can select which tasks she/he wants to send to an other viewController.
我已经制作了一个表格视图,它允许用户将任务添加到表格视图中,但是现在我需要在每个任务前面添加一个复选框,以便用户可以选择她/他想要发送到哪些任务其他视图控制器。
After I googled it, I realized that there is no checkBox or radioButton in swift, I should create my own "boxChecked.png" and "boxUnchecked.png",
在我用谷歌搜索之后,我意识到 swift 中没有 checkBox 或 radioButton,我应该创建我自己的“boxChecked.png”和“boxUnchecked.png”,
Here is a piece of my code which gives me an error:
这是我的一段代码,它给了我一个错误:
if (selectedIndex == indexPath) {
cell.radioButton?.setImage(UIImage(named: "boxChecked"),forState:UIControlState.Normal)
} else {
cell.radioButton?.setImage(UIImage(named: "boxUnchecked"),forState:UIControlState.Normal)
}
and the error it gives me is:
它给我的错误是:
'UITableViewCell?' does not have a member named 'radiobutton'
even though I tried creating a class named TableViewCell which is a subclass of UITableViewCell, and declared the variable radioButtonin it like:
即使我尝试创建一个名为 TableViewCell 的类,它是 UITableViewCell 的子类,并在其中声明了变量radioButton如下:
@IBOutlet weak var radioButton: UIButton!
but it still didn't work.
但它仍然没有用。
Here is the code of func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath):
这是func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) 的代码:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell")
if (selectedIndex == indexPath) {
cell.radioButton?.setImage(UIImage(named: "boxChecked"),forState:UIControlState.Normal)
} else {
cell.radioButton?.setImage(UIImage(named: "boxUnchecked"),forState:UIControlState.Normal)
}
cell.textLabel?.textAlignment = .Right
cell.detailTextLabel?.textAlignment = .Left
cell.textLabel?.text = taskMgr.tasks[indexPath.row].name
cell.detailTextLabel?.text = taskMgr.tasks[indexPath.row].score
return cell
//let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Default")
// cell.textLabel?.text = taskMgr.tasks[indexPath.row].name
// cell.detailTextLabel?.text = taskMgr.tasks[indexPath.row].desc
//return cell
}
回答by Alexander
Try this code:
试试这个代码:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "cell"
var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? TableViewCell
if cell == nil {
cell = TableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: cellIdentifier)
}
if (selectedIndex == indexPath) {
cell!.radioButton?.setImage(UIImage(named: "boxChecked"),forState:UIControlState.Normal)
} else {
cell!.radioButton?.setImage(UIImage(named: "boxUnchecked"),forState:UIControlState.Normal)
}
cell!.textLabel?.textAlignment = .Right
cell!.detailTextLabel?.textAlignment = .Left
cell!.textLabel?.text = taskMgr.tasks[indexPath.row].name
cell!.detailTextLabel?.text = taskMgr.tasks[indexPath.row].score
return cell!
}
回答by Departamento B
You should instantiatie your custom table view cell like this if you're using Interface Builder:
如果您使用的是 Interface Builder,您应该像这样实例化您的自定义表格视图单元格:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCellWithIdentifier("IdentifierInInterfaceBuilder") as? MyCustomTableViewCell else {
return UITableViewCell()
}
return cell
}
Set up your cell in IB like this:
像这样在 IB 中设置您的单元格:
I think your approach might be more difficult than necessary. When you have a UITableViewCell the standard (not custom ones) allow for text and an image. If you set the image through Interface Builder (or programmatically) you can set a normal and a highlightedimage value. This will use the selected image whenever the cell is selected and the other when it isn't.
我认为你的方法可能比必要的更困难。当你有一个 UITableViewCell 时,标准(不是自定义的)允许文本和图像。如果您通过 Interface Builder(或以编程方式)设置图像,您可以设置正常和突出显示的图像值。这将在选择单元格时使用选定的图像,而在未选择时使用另一个图像。
This also means now that a regular selection action will be enough, making the whole table view cell a hotspot and you can very simply get the selected cells and the events for selecting and unselecting through the built-in delegates and functions.
这也意味着现在常规选择操作就足够了,使整个表格视图单元格成为热点,您可以非常简单地通过内置委托和函数获取选定的单元格以及用于选择和取消选择的事件。
For more complex approaches not falling within the possibilities of a Plain UITableViewCell you can use the highlighted value for a UIImageView and change it after either selecting or when you load it at first.
对于不属于普通 UITableViewCell 可能性的更复杂的方法,您可以使用 UIImageView 的突出显示值并在选择或首先加载它后更改它。
class ExampleTableViewCell: UITableViewCell {
@IBOutlet var checkMark: UIImageView?
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
checkMark?.highlighted = selected
}
}
Do you see how little code it requires and how it just works with the flow of the way the UITableView works?
你看到它需要多少代码以及它是如何与 UITableView 工作方式的流程一起工作的吗?
回答by FreeNickname
You have a UITableView
. It uses cells to display content. There is one built-in default implementation of a cell: UITableViewCell
. In order to customize UITableViewCell
appearance, we create custom cells like you did with the TableViewCell
class. Bring it back if you deleted it.
你有一个UITableView
. 它使用单元格来显示内容。单元格有一个内置的默认实现:UITableViewCell
. 为了自定义UITableViewCell
外观,我们创建自定义单元格,就像您在TableViewCell
类中所做的那样。如果你删除了它,把它找回来。
UITableView
reuses cells for efficiency. When the cell goes off screen, it is saved, and when the table view needs the same kind of cell later, it doesn't recreate it every time. It takes it from its cache (if it is not empty).
UITableView
重复使用细胞以提高效率。当单元格离开屏幕时,它会被保存,当表格视图稍后需要相同类型的单元格时,它不会每次都重新创建它。它从它的缓存中获取它(如果它不为空)。
There may be several different kinds of cells in a table view (e.g. user info cell, tasks cells, etc.). In order to understand, what kind of cell the table view should create/get from cache, reuseIdentifer
is used. reuseIdentifer
denotes a kind of cell. So, there should be some way to tell the tableView
, that when we request a "RadioButtonCell"
(for instance), we want it to create a cell with class TableViewCell
(your custom subclass).
表格视图中可能有几种不同类型的单元格(例如用户信息单元格、任务单元格等)。为了理解,使用了表格视图应该从缓存中创建/获取的单元格类型reuseIdentifer
。reuseIdentifer
表示一种细胞。因此,应该有某种方式告诉tableView
,当我们请求一个"RadioButtonCell"
(例如)时,我们希望它创建一个带有类TableViewCell
(您的自定义子类)的单元格。
There are several ways to do that. It can be done via storyboards, it can be done through code. If your cell has a xib
(interface file) associated with it, you can do it using
有几种方法可以做到这一点。它可以通过故事板完成,也可以通过代码完成。如果您的单元格有一个xib
(接口文件)与之关联,您可以使用
tableView.registerNib(UINib(nibName: "TableViewCell", bundle: nil)), forCellReuseIdentifier: "RadioButtonCell")
If you didn't create an interface file for it, you can do it using
如果您没有为其创建接口文件,则可以使用
tableView.registerClass(..., forCellReuseIdentifier: ...)
method.
方法。
You can register nibs once (for instance, inside viewDidLoad).
Then later in cellForRowAtIndexPath
you do:
您可以注册一次笔尖(例如,在 viewDidLoad 中)。然后稍后cellForRowAtIndexPath
你会做:
var cell: TableViewCell = tableView.dequeueReusableCellWithIdentifier("RadioButtonCell)
and customize this cell as you did in your question.
并像您在问题中所做的那样自定义此单元格。
回答by hasan
Did you changed the type of the UITableViewCell
using the interface builder to your custom UITableViewCell
您是否将UITableViewCell
使用界面构建器的类型更改为您的自定义UITableViewCell
Select your cell > Select the Identity Inspector in the right pane > change the class to your custom UITableViewCell class name.
选择您的单元格 > 在右侧窗格中选择身份检查器 > 将类更改为您自定义的 UITableViewCell 类名。
You need also to connect the check button view with the outlet in your custom class.
您还需要将检查按钮视图与自定义类中的插座连接起来。
You also need to add 2 UILabels one for the title and one for the details and connect them too.
您还需要添加 2 个 UILabels,一个用于标题,另一个用于详细信息,并将它们也连接起来。