我想在长按时在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];
}];
}}
但问题是它仅适用于第一个集合视图单元格长按和剩余单元格它不会显示任何标签。 请告诉我我的代码有什么问题?
答案 0 :(得分:0)
我已通过更改此行来解决此问题:
lblImageName = [[UILabel alloc] initWithFrame:CGRectMake(cell.frame.origin.x, cell.frame.origin.y, 200, 200)];
为:
lblImageName = [[UILabel alloc] initWithFrame:CGRectMake(0,0, 200, 200)];