gpt4 book ai didi

ios - UICollectionView 自定义单元格在我滚动时自动刷新

转载 作者:行者123 更新时间:2023-11-29 10:51:15 28 4
gpt4 key购买 nike

我有一个 UICollectionView 和自定义 UICollectionViewCell,我在其中加载图像,当我滚动 UICollectionView 时,我看到了所有单元格正在刷新,这是 UICollectionView delegates,

的代码

ViewDidLoad 中首先添加这个以添加 CustomCell

 -(void)ViewdidLoad{
UINib *nib = [UINib nibWithNibName:@"NMCFAIPadWishListCell" bundle:nil];
[self.accountDetailsCollectionView registerNib:nib forCellWithReuseIdentifier:@"Cell"];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return [[self wishListData] count];

}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

static NSString *identifier = @"Cell";

NMCFAIPadWishListCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
[cell setWishList:[[self wishListData] objectAtIndex:[indexPath row]] delegate:self];
return cell;
}

setWishList 方法中,只需将数组中的值分配给标签,我在 Xib 中为自定义 UICollectionViewCell 中的每个单元格设置了一个按钮,当用户点击该按钮时,我只是在更改标签 BG 颜色

 - (void)setWishList:(NSString*)product delegate:(id)delegate
{
self.label.text = product;
}

下面是按钮 Action

- (IBAction)editProduct:(id)sender
{
self.label.backgroundColor = [UIColor redColor];
}

我的问题是,当我滚动自定义单元格并点击任何单元格中的按钮时,标签 BG 不仅在当前单元格中发生变化,而且在许多单元格中也发生变化。

最佳答案

您不应尝试在单元格中/单元格上存储任何状态,因为单元格对象本身会根据 UICollectionView 的判断重用。

您的问题的一个解决方案可能是:

  • 在您的 editProduct: 方法中(假设您的 editProduct: 方法在您的自定义 UICollectionViewCell 实现中),通知 Collection View 的 Controller 用户通过协议(protocol)方法(或 block 或其他一些消息传递机制)“选择”了该产品。
  • 在您的 View Controller 中,当收到上述消息时,识别点击按钮的单元格的索引(indexPathForCell: 在这里可能有用)并存储索引 n< 处的项目/em> 已被选中。 NSArray 在这里可能会有用。
  • 以相同的方法,强制重新加载已被 reloadItemsAtIndexPaths: 窃听的单元格或类似的方法。这将强制调用 collectionView:cellForRowAtIndexPath: 方法。
  • 在您的 collectionView:cellForRowAtIndexPath: 方法中实现如下内容:

    BOOL itemSelected = ((NSNumber *)isProductSelectedArray[indexPath.row]).boolValue; // You can't store `BOOL`s directly into NSArrays. So I've assumed an NSNumber here.
    cell.backgroundColor = itemSelected ? [UIColor redColor] : [UIColor clearColor] // Or some other color to indicate non-selection.

顺便说一句,如果您声明“ViewdidLoad”而不是“viewDidLoad”,您可能会发现您的代码没有按您预期的方式运行。不要忘记在您的实现中的某处调用 [super viewDidLoad]。

最后,我建议阅读“Collection View Basics”以更好地理解单元重用的概念。 Apple 的“iOS Collection View 编程指南”一章 - 特别是标题为“可重用 View 提高性能”的部分。

关于ios - UICollectionView 自定义单元格在我滚动时自动刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20381244/

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