我有一个 UITableView,其中每个单元格都有一个按钮.
单击按钮时,单元格的高度将发生变化.
当然,整个tableview的高度会根据它来改变.
在长时间冲浪时我找不到路.实现这一目标的优雅解决方案是什么?
I have a UITableView, in which each cell has a button.
When the button is clicked, the cell's height will be changed.
Of course, the whole tableview height will be changed according to it.
I cannot find a way during long surfing.
What is an elegant solution to achieve this?
(请参阅 this 答案.赞Tapas Pal 以编写原始答案.我只是将其更改为更适合您的问题.)
(See this answer. Kudos to Tapas Pal for writing the original answer. I just changed it to better fit your question.)
您将需要一个 BOOL
变量来告诉单元格它的高度应该与其他的不同.您还需要一个数字(这里,我将使用 NSInteger
)变量,以便您可以增加右侧单元格的高度.
You will need a BOOL
variable to tell the cell that its height should be different from the others. You will also need a number (here, I will use NSInteger
) variable so that you can increase the height for the right cell.
BOOL shouldCellBeExpanded = NO;
NSInteger indexOfExpandedCell = -1;
然后,在您的 -tableView:cellForRowAtIndexPath:
方法中,将以下内容添加到您设计单元格的位置.您将按钮标记设置为与其单元格的行相同,以便您知道要展开哪个单元格.此外,如果您需要向单元格添加任何元素,可以在 if
语句中进行.
Then, in your -tableView:cellForRowAtIndexPath:
method, add the following to where you design your cell. You will set the button tag to be the same as its cell's row so that you know what cell to expand. Moreover, if you need to add any elements to the cell, you can do it inside the if
statement.
[[cell aButton] setTag:[indexPath row]];
if(shouldCellBeExpanded && [indexPath row] == indexOfExpandedCell)
{
// design your read more label here
}
移动到按钮的 IBAction
.当点击按钮时,UITableView
将重新加载按钮所在的单元格.注意:如果您在 UITableView
中使用多个部分,则需要添加另一个数字变量来解决此问题.如果您需要帮助,请发表评论.
Moving to the button's IBAction
. When the button is tapped, the UITableView
will reload the cell that button is on. Note: if you use multiple sections in your UITableView
, you will need to add another number variable to account for that. Comment if you need help.
-(IBAction) aButtonTapped:(id)sender
{
UIButton *aButton = (UIButton *)sender;
indexOfExpandedCell = [aButton tag];
shouldCellBeExpanded = YES;
[[self tableView] beginUpdates];
[[self tableView] reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForItem: indexOfExpandedCell inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];
[[self tableView] endUpdates];
}
最后,在-tableView:heightForRowAtIndexPath:
方法中:
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(shouldCellBeExpanded && [indexPath row] == indexOfExpandedCell)
return 200.0f; //Your desired height for the expanded cell
else
return 100.0f; //The other cells' height
}
它的作用是检查一个单元格是否应该被扩展,如果是,那么该单元格是否是当前被要求提供高度值的那个单元格.如果是,则返回值是展开后的高度.如果没有,请使用原始版本.
What this does is check if a cell is expected to be expanded and, if so, whether that cell is the one currently being asked for a height value. If it is, then the returned value is the expanded height. If not, the original one.
这篇关于UITableView:单击按钮时如何动态更改单元格高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!