ios - 如何在 CollectionView 中选择单个单元格并取消选择所有其他单元格
<p><p>**</p>
<blockquote>
<p>I have horizontal CollectionView in which selected cell have orange
gradient color and all other deselected cells gray color i m
using only didselect delegate method but i am getting problem of
multiple cells selected and i have problem with same concept in table
view while scrolling and i have searched a lot but i have not get
proper answer of cell reusability</p>
</blockquote>
<p>**</p>
<pre><code>- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
DateTimeCell * cell = ;
if (self.selectedIndexPath != nil && indexPath == self.selectedIndexPath)
{
CAGradientLayer *gradient = ;
gradient.frame = cell.mainView.bounds;
gradient.startPoint = CGPointZero;
gradient.endPoint = CGPointMake(1, 1);
gradient.colors = CGColor],(id)[ CGColor], nil];
;
cell.mainView.backgroundColor = ;
;
;
}
else
{
];
}
return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
indexPaths = ;
if (self.selectedIndexPath)
{
// if we had a previously selected cell
if ( == NSOrderedSame)
{
// if it's the same as the one we just tapped on, then we're unselecting it
NSLog(@"Selected");
}
else
{
// if it's different, then add that old one to our list of cells to reload, and
// save the currently selected indexPath
;
self.selectedIndexPath = indexPath;
}
}
else
{
// else, we didn't have previously selected cell, so we only need to save this indexPath for future reference
self.selectedIndexPath = indexPath;
}
dispatch_async(dispatch_get_main_queue(), ^{
;
});
}
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>像下面这样全局获取一个全局 selectedIndexPath</p>
<pre><code>NSIndexPath *selectedIndexPath = [ indexPathForRow:0 inSection:0];
</code></pre>
<p>在委托(delegate)方法中编写下面的代码</p>
<pre><code>- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
DateTimeCell * cell = ;
if self.selectedIndexPath == indexPath
{
// do what you want to do with your selected cell
}
else
{
// do what you want to do with your deselected cell
}
return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
self.selectedIndexPath = indexPath
;
}
</code></pre></p>
<p style="font-size: 20px;">关于ios - 如何在 CollectionView 中选择单个单元格并取消选择所有其他单元格,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/42592767/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/42592767/
</a>
</p>
页:
[1]