iOS:长按时在 uicollectionViewcell 上显示带有文本的标签
Posted
技术标签:
【中文标题】iOS:长按时在 uicollectionViewcell 上显示带有文本的标签【英文标题】:iOS:Dispaly label with text on collectionView cell on long press 【发布时间】:2015-01-03 06:14:17 【问题描述】:我想在长按时在 collectionViewCell 上显示带有文本的标签。 我要显示的文本来自数组。
以下是我的代码:
// This code is in cellForItemAtIndexPath method
// attach long press gesture to collectionView
UILongPressGestureRecognizer *lpgr= [[UILongPressGestureRecognizer alloc]
initWithTarget:self action:@selector(handleLongPress:)];
lpgr.minimumPressDuration = .5; //seconds
lpgr.delegate = self;
[collectionViewAlbumImages addGestureRecognizer:lpgr];
lpgr.delaysTouchesBegan = YES;
-(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer
if (gestureRecognizer.state != UIGestureRecognizerStateEnded)
return;
CGPoint p = [gestureRecognizer locationInView:collectionViewAlbumImages];
NSIndexPath *indexPath = [collectionViewAlbumImages indexPathForItemAtPoint:p];
if (indexPath == nil)
NSLog(@"couldn't find index path");
else
// get the cell at indexPath (the one you long pressed)
UICollectionViewCell* cell =[collectionViewAlbumImages cellForItemAtIndexPath:indexPath];
globalVariable = [GlobalBrogaard sharedInstanceMethod];
strCellImageName = [NSString stringWithFormat: @"%@",[globalVariable.arrImageName objectAtIndex:indexPath.row]];
NSLog(@"cell %f , %f",cell.frame.origin.x, cell.frame.origin.y);
// Init and add label
lblImageName = [[UILabel alloc] initWithFrame:CGRectMake(cell.frame.origin.x, cell.frame.origin.y, 200, 200)];
lblImageName.layer.cornerRadius=6;
lblImageName.clipsToBounds=NO;
lblImageName.text = strCellImageName;
[lblImageName setTextAlignment:NSTextAlignmentLeft];
lblImageName.lineBreakMode = NSLineBreakByCharWrapping;
lblImageName.numberOfLines = 0;
lblImageName.font = [UIFont systemFontOfSize:14];
lblImageName.textColor = [UIColor whiteColor];
lblImageName.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.6];
[lblImageName sizeToFit];
[cell addSubview:lblImageName];
[lblImageName setAlpha:0.0f];
//fade in
[UIView animateWithDuration:2.0f animations:^
[lblImageName setAlpha:1.0f];
completion:^(BOOL finished)
//fade out
[UIView animateWithDuration:2.0f animations:^
[lblImageName setAlpha:0.0f];
[lblImageName removeFromSuperview];
completion:nil];
];
但问题是它仅适用于第一个集合视图单元格长按,并且在剩余的单元格上它不会显示任何标签。 请告诉我我的代码有什么问题??
【问题讨论】:
【参考方案1】:我已经通过改变这一行解决了这个问题:
lblImageName = [[UILabel alloc] initWithFrame:CGRectMake(cell.frame.origin.x, cell.frame.origin.y, 200, 200)];
到:
lblImageName = [[UILabel alloc] initWithFrame:CGRectMake(0,0, 200, 200)];
【讨论】:
以上是关于iOS:长按时在 uicollectionViewcell 上显示带有文本的标签的主要内容,如果未能解决你的问题,请参考以下文章
IOS:通过长按选择 UICollectionView 单元格