ios 在UICollectionView上最多选择4个图像

wqsoz72f  于 2022-12-15  发布在  iOS
关注(0)|答案(3)|浏览(170)

如果用户选择超过4张图像,则显示警报框。

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *secell = [collectionView cellForItemAtIndexPath:indexPath];

    if (indexPath.row == 4) {

        UIAlertView * alert =[[UIAlertView alloc ] initWithTitle:@"OK Dailog"
                                                         message:@"This is OK dialog"
                                                        delegate:self
                                               cancelButtonTitle:@"Cancel"
                                               otherButtonTitles: nil];
        [alert show];
    }

    else
    {
        UIImageView *imgselect = (UIImageView *)[secell viewWithTag:110];
        imgselect.image = [UIImage  imageNamed:@"selectimg.png"];
    }

}
pcrecxhr

pcrecxhr1#

您应该检查所选项目的数量,而不是检查indexPath.row。可以尝试类似的操作

NSArray *selectedIndexPaths =  [collectionView  indexPathsForSelectedItems];

if (selectedIndexPaths.count > 4)
{
   // Show alert
}
vx6bjr1n

vx6bjr1n2#

这应该在委托方法collectionView:shouldSelectItemAtIndexPath中设置

- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    BOOL shouldSelect = collectionView.indexPathsForSelectedItems.count < 4;
    if (!shouldSelect) {
        // Show Alert
    }
    return shouldSelect;
}
cgyqldqp

cgyqldqp3#

适用于swift 5

func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
        let shouldSelect = (collectionView.indexPathsForSelectedItems?.count ?? 0) < 4
        if !shouldSelect {
            // show alert here
        }
        return shouldSelect
    }

相关问题