gpt4 book ai didi

iphone - 当点击iPhone中的UIButton时如何保持选中状态?

转载 作者:行者123 更新时间:2023-12-03 19:37:20 36 4
gpt4 key购买 nike

我创建了三个按钮并设置了正常状态和选定状态的背景图像。当我单击按钮时,将一张图像更改为选定状态。但是当滚动表格 View 时,选定的图像不会保留(之前选定的单元格),这意味着它处于正常状态。

我的代码是,

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

likeBtn = [UIButton buttonWithType:UIButtonTypeCustom];

UIImage *likeSelectedImage = [UIImage imageNamed:@"like.png"];

//set image as background for button in the normal state

[likeBtn setBackgroundImage:likeSelectedImage forState:UIControlStateNormal];

[likeBtn addTarget:self action:@selector(likeAction:) forControlEvents:UIControlEventTouchUpInside];

[cell.contentView addSubview:likeBtn];
}

我的按钮操作是,

 -(void) likeAction : (id) sender
{
UIImage *likeSelectedImg = [UIImage imageNamed:@"like-selected.png"];

UIImage *likeImg = [UIImage imageNamed:@"like.png"];

if ([sender isSelected]) {
[sender setImage:likeImg forState:UIControlStateNormal];
[sender setSelected:NO];
}else {
[sender setImage:likeSelectedImg forState:UIControlStateSelected];
[sender setSelected:YES];
}

}

所以我的问题是,当我滚动表格 View 单元格时,之前选择的图像状态不会保留。因为当我滚动表格时,cellForRowAtIndex方法被重复调用。所以它会自动设置“[likeBtn setBackgroundImage:likeSelectedImage forState:UIControlStateNormal];”。如何避免这个问题呢?那么请帮帮我吗?谢谢!

最佳答案

您看到这种情况是由于 UITableView 用于显示数据的设计模式所致。为了最大限度地减少资源使用,仅保证当前屏幕上的表格单元格保留在内存中。当单元格滚动到屏幕外时,单元格对象将被回收以用于出现在列表另一端的新单元格,因此会丢失其状态。

我假设您在返回 tableView: cellForRowAtIndexPath: 中的单元格时对代码进行了一些修剪,但您发布的代码片段中的其他任何地方都没有对该变量的引用。这使得在添加按钮之前无法查看如何获取单元格。

关于您的代码如何工作,有点摸不着头脑,但这里是您需要做什么来保留状态的高级概述。

  1. 创建一些 Controller 级存储(例如 NSArray)来保存所有表行的所有按钮状态。
  2. likeAction 中确定按钮来自哪一行(可能在创建按钮时将行号分配给按钮的标签属性)并更新 NSArray 中相应行的状态
  3. tableView: cellForRowAtIndexPath: 中,使用从给定索引路径的 NSArray 中获取的状态,使用正确的图像设置按钮。

关于iphone - 当点击iPhone中的UIButton时如何保持选中状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4658345/

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