gpt4 book ai didi

ios - UITableViewCell 添加按钮

转载 作者:行者123 更新时间:2023-11-28 22:12:02 24 4
gpt4 key购买 nike

我想在自定义单元格中添加一些按钮,当我点击按钮时,其他按钮也会发生变化。如何在不更改其他按钮的情况下单击一个按钮?

enter code here
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier = @"cell";
SViewTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
cell = [[SViewTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:identifier];
}
cell.cellButton.tag = indexPath.row;
[cell.cellButton addTarget:self action:@selector(clickMe:)
forControlEvents:UIControlEventTouchUpInside];

return cell;
}

- (void)clickMe:(UIButton *)sender
{
SViewTableViewCell *cell = (SViewTableViewCell *)[[sender superview]superview];
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];

if (sender.tag == 0) {
if ([sender.titleLabel.text isEqualToString:openStr]) {
[sender setTitle:closeStr forState:UIControlStateNormal];
}
else{
[sender setTitle:openStr forState:UIControlStateNormal];
}
}
}

最佳答案

我认为这是关于 tableView 单元格重用的问题,您应该在 cellForRow 中设置按钮标题以保持重用单元格具有正确的标题,您应该尝试这样的代码:

openDict 是您应该定义的 NSMutableArray,这只是一个示例。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier = @"cell";
SViewTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
cell = [[SViewTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:identifier];
[cell.cellButton addTarget:self action:@selector(clickMe:)
forControlEvents:UIControlEventTouchUpInside];
}

NSString *key = [NSString stringWithFormat:@"%d-%d", indexPath.row, indexPath.section];
if (openDict[key] && [openDict[key] boolValue]) {
[sender setTitle:openStr forState:UIControlStateNormal];
}
else{
[sender setTitle:closeStr forState:UIControlStateNormal];
}

cell.cellButton.tag = indexPath.row;
return cell;
}

- (void)clickMe:(UIButton *)sender
{
SViewTableViewCell *cell = (SViewTableViewCell *)[[sender superview]superview];
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];

if (sender.tag == 0) {
NSString *key = [NSString stringWithFormat:@"%d-%d", indexPath.row, indexPath.section];
if (openDict[key] && [openDict[key] boolValue]) {
openDict[key] = @(0);
[sender setTitle:closeStr forState:UIControlStateNormal];
}
else{
openDict[key] = @(1);
[sender setTitle:openStr forState:UIControlStateNormal];
}
}
}

关于ios - UITableViewCell 添加按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22677201/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com