我有UICollectionView
个自定义单元格,我想在其中显示一些倒计时。我遇到的问题是,当我有一个带倒计时的单元格并将其向下滚动时,其中不应该有倒计时的单元格也会显示倒计时。
我知道这与细胞的重复使用有关,但不确定我该怎么办。这是我的代码:
cellForItemAtIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
MainCell *cell = (MainCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"MainCell" forIndexPath:indexPath];
if(displayCountDown.boolValue){
NSDate *endTime = [offer objectForKey:@"expiresDate"];
[cell startTimer:endTime];
cell.imgTimeLeftClock.hidden = NO;
}else{
cell.lblTimeLeft.text = @"No time limit";
cell.imgTimeLeftClock.hidden = YES;
}
return cell;
}
在MainCell.m内部:
- (void) startTimer :(NSDate *) endTime
{
[self.timer invalidate];
self.startTime = [NSDate date];
self.endTime = endTime;
double startTimeDouble = [self.startTime timeIntervalSince1970];
int currentTimeRound = (int)startTimeDouble;
double endTimeDouble = [self.endTime timeIntervalSince1970];
int endTimeRound = (int)endTimeDouble;
self.secondsLeft = endTimeRound - currentTimeRound;
// create a new timer
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(calculateTimer) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
[self.timer fire];
}
- (void)calculateTimer
{
self.secondsLeft--;
if(self.secondsLeft > 0){
int days = self.secondsLeft / 86400;
int hours = (self.secondsLeft / 3600) % 24;
int minutes = (self.secondsLeft % 3600) / 60;
int seconds = (self.secondsLeft %3600) % 60;
self.lblTimeLeft.text = [NSString stringWithFormat:@"%02d:%02d:%02d:%02d", days, hours, minutes, seconds];
}else{
self.lblTimeLeft.text = @"Time's up";
}
}
我能做些什么才能让倒计时只显示在正确的细胞上?
答案 0 :(得分:1)
你应该使用在数组中存储具有计时器的单元格(即timerArray)并使用此数组向该单元格添加计时器,如下所示,
-(NSInteger)collectionView:(UICollectionView *)collectionView
numberOfItemsInSection:(NSInteger)section
{
return collectionViewArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
MainCell *cell = (MainCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"MainCell" forIndexPath:indexPath];
if(displayCountDown.boolValue){
//In place of this bool check you could simply check if that object(collectionViewArray) is in your timerArray.
//Your timerArray will contain obj which are having timer in it and collectionViewArray is your array having all objects(with/without timer and is actual array that you use for count)
//Then if-else condition will go similarly.
NSDate *endTime = [offer objectForKey:@"expiresDate"];
[cell startTimer:endTime];
cell.imgTimeLeftClock.hidden = NO;
}else{
cell.lblTimeLeft.text = @"No time limit";
cell.imgTimeLeftClock.hidden = YES;
}
return cell;
}
希望这能帮到你!
答案 1 :(得分:0)
您在cellForItem中的逻辑基于displayCountDown.boolValue,但它也应该基于单元格的indexPath。因此,每次调用cellForItem时,您都知道哪个单元格应该显示标签以及何时应该隐藏它。您可以根据索引路径打开或关闭它。 否则就像你说集合视图将重用它。