You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Objective-C实现UICollectionViewListCell侧滑删除:求示例及补全问题排查

UICollectionViewListCell侧滑删除(Objective-C)实现及编译器补全问题原因

编译器无法自动补全的常见原因

  • UICollectionLayoutListConfiguration在Objective-C中是不可变对象,不能像Swift那样直接赋值属性,需通过构造方法的配置逻辑或setter方法设置,直接赋值会导致编译器无法识别属性,进而无法触发自动补全。
  • 未将项目部署目标设置为iOS 14.0+(UICollectionViewListCell和UICollectionLayoutListConfiguration是iOS 14新增API),低版本环境下编译器不会识别这些API。
  • 头文件导入不完整,需确保代码中导入<UIKit/UIKit.h>,或在项目前缀文件中全局导入。

Objective-C示例代码

// 创建列表布局配置
UICollectionLayoutListConfiguration *listConfig = [UICollectionLayoutListConfiguration configurationWithAppearance:UICollectionLayoutListAppearanceInsetGrouped];

// 设置右侧侧滑动作配置
[listConfig setTrailingSwipeActionsConfigurationProvider:^UISwipeActionsConfiguration * _Nonnull(NSIndexPath * _Nonnull indexPath) {
    __weak typeof(self) weakSelf = self;
    // 创建删除动作
    UIContextualAction *deleteAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive title:@"删除" handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
        // 执行删除逻辑:更新数据源、移除对应cell
        [weakSelf.dataArray removeObjectAtIndex:indexPath.item];
        [weakSelf.collectionView deleteItemsAtIndexPaths:@[indexPath]];
        // 告知系统动作完成
        completionHandler(YES);
    }];
    // 配置动作背景色(可选)
    deleteAction.backgroundColor = [UIColor systemRedColor];
    // 返回侧滑动作配置
    return [UISwipeActionsConfiguration configurationWithActions:@[deleteAction]];
}];

// 创建列表布局
UICollectionViewCompositionalLayout *layout = [UICollectionViewCompositionalLayout layoutWithListConfiguration:listConfig];
// 初始化CollectionView
UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
collectionView.dataSource = self;
// 注册UICollectionViewListCell
[collectionView registerClass:[UICollectionViewListCell class] forCellWithReuseIdentifier:@"ListCellID"];
[self.view addSubview:collectionView];

关键注意点

  • 使用__weak typeof(self) weakSelf = self;避免block持有self导致的循环引用。
  • 侧滑动作样式选择UIContextualActionStyleDestructive对应删除类的红色警示样式,UIContextualActionStyleNormal为普通操作样式。
  • 动作执行完成后必须调用completionHandler(BOOL),通知系统结束侧滑状态。

内容的提问来源于stack exchange,提问作者Ofir Malachi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 03:50:17