gpt4 book ai didi

ios - 在 UITableViewCell 中添加自定义编辑和删除按钮

转载 作者:行者123 更新时间:2023-12-01 18:48:29 24 4
gpt4 key购买 nike

我有一个 UITableView其中包含所有国家的名称。
用户可以随时通过点击cell 删除或编辑国家名称。 .

我的 UITableView 单元格最初看起来像这样:

enter image description here

现在当用户点击它时,我正在改变它:

enter image description here

我想我正在遵循一种非常蹩脚的方法。这就是我所做的:

全局声明要添加的按钮:

 UIButton *btnDeleteWithImage,*btnDeleteWithText,*btnEditWithImage,*btnEditWihtText; //buttons

还有一个 NSMutableArray跟踪 indexPath.row
现在在我的 didSelectMethod 中,我正在这样做:
 //To change the background 
UIView *selectionBackground = [[UIView alloc] init];

selectionBackground.backgroundColor = [UIColor customColor];

cell.selectedBackgroundView = selectionBackground;

// to check which cell is pressed

if([indexPathCollection containsObject:index])
{
[btnDeleteWithImage removeFromSuperview];
[btnDeleteWithText removeFromSuperview];
[btnEditWihtText removeFromSuperview];
[btnEditWithImage removeFromSuperview];
[indexPathCollection removeObject:index];

[cell addSubview:btnDeleteWithImage];
[cell addSubview:btnDeleteWithText];
[cell addSubview:btnEditWithImage];
[cell addSubview:btnEditWihtText];
[indexPathCollection addObject:index];
}
else
{

[cell addSubview:btnDeleteWithImage];
[cell addSubview:btnDeleteWithText];
[cell addSubview:btnEditWithImage];
[cell addSubview:btnEditWihtText];
[indexPathCollection addObject:index];
}

但这不好用。当我滚动表时,随机出现编辑和删除按钮。

有人有更好的想法如何以非常有效的方式实现这一目标。

最佳答案

您可以通过使用您的属性创建自定义单元格来实现此目的

自定义单元格.h

@interface CustomCell : UITableViewCell

@property (nonatomic, strong) UIButton *btnDeleteWithImage;
@property (nonatomic, strong) UIButton *btnDeleteWithText;
@property (nonatomic, strong) UIButton *btnEditWithImage;
@property (nonatomic, strong) UIButton *btnEditWithText;

@end

在单元格的 init 方法中初始化它们,首先将它们隐藏起来,或者你可以这样做
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

static NSString *customCellIdentifier = @"customCellIdentifier";
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:customCellIdentifier];

if (!cell) {
cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:customCellIdentifier];
// or you can initialize and add them to the cell here
}
//here you can modify them accordingly
return cell;
}

那么委托(delegate)方法可以是
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

CustomCell *cell = [tableView cellForRowAtIndexPath:indexPath];
[cell.btnDeleteWithImage setHidden:NO];
[cell.btnEditWithImage setHidden:NO];
}

关于ios - 在 UITableViewCell 中添加自定义编辑和删除按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33074107/

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