I have this code as following. I am trying to add a subview with background color red to my selected tableView cell. But I am facing two bugs:
我有这样的代码如下。我正在尝试将背景颜色为红色的子视图添加到我选择的tableView单元格中。但我面临两个错误:
1: The height of the tableView Cell is 44, but when I set my subView's height to be 44, it seems to be half of the cell height. I can only make the two views equal when the subView frame height is set to be 88.
1:tableView Cell的高度为44,但是当我将subView的高度设置为44时,它似乎是单元格高度的一半。当subView框架高度设置为88时,我只能使两个视图相等。
2: The subView only shows up when I tab it twice. If I tab it for only once, The sub View doesn't show up.
2:当我选中它两次时,子视图才会显示。如果我只选择一次,则子视图不会显示。
BTW: I have two tableViews in one viewController, so please look at the tableView inside of "else".
顺便说一句:我在一个viewController中有两个tableView,所以请查看“else”中的tableView。
1 个解决方案
#1
1
The problem in you code is that you try to add selectedBar view directly to selectedCell and this isn't valid you must add it to contentView of selectedCell
您的代码中的问题是您尝试将selectedBar视图直接添加到selectedCell,这是无效的您必须将其添加到selectedCell的contentView
like this
selectedCell.contentView.addSubview(selectedBar)
Also selectedBar is shown when you tap twice because you must add this to the end of didSelectRowAt
当您点击两次时也会显示selectedBar,因为您必须将其添加到didSelectRowAt的末尾
tableView.deselectRow(at: indexPath, animated: false)
// Edit -> add tag of 555 when you create the view
//编辑 - >创建视图时添加555的标记
add this code in cellForRowAt
在cellForRowAt中添加此代码
if(index == indexpath.row)
{
// add the view here
}
else
{
for i in 0..<selectedCell.contentView.subviews.count
{
let cv = selectedCell.contentView.subviews[i]
if cv.tag == 555
{
cv.removeFromSuperview()
}
}
}
Note: when you select didSelectCellAt update only the index to indexpath.row
注意:当您选择didSelectCellAt时,仅更新indexpath.row的索引
and reload the table
并重新加载表
#1
1
The problem in you code is that you try to add selectedBar view directly to selectedCell and this isn't valid you must add it to contentView of selectedCell
您的代码中的问题是您尝试将selectedBar视图直接添加到selectedCell,这是无效的您必须将其添加到selectedCell的contentView
like this
selectedCell.contentView.addSubview(selectedBar)
Also selectedBar is shown when you tap twice because you must add this to the end of didSelectRowAt
当您点击两次时也会显示selectedBar,因为您必须将其添加到didSelectRowAt的末尾
tableView.deselectRow(at: indexPath, animated: false)
// Edit -> add tag of 555 when you create the view
//编辑 - >创建视图时添加555的标记
add this code in cellForRowAt
在cellForRowAt中添加此代码
if(index == indexpath.row)
{
// add the view here
}
else
{
for i in 0..<selectedCell.contentView.subviews.count
{
let cv = selectedCell.contentView.subviews[i]
if cv.tag == 555
{
cv.removeFromSuperview()
}
}
}
Note: when you select didSelectCellAt update only the index to indexpath.row
注意:当您选择didSelectCellAt时,仅更新indexpath.row的索引
and reload the table
并重新加载表