iOS开发使用UITableView制作N级下拉菜单的示例

2020-01-21 04:20:41王振洲

第三步, 设置选项模型, 添加辅助属性

LTMenuItem 类添加几个辅助属性, 用于表示选中和展开闭合

     isSelected : 用于表示选项的选中状态 isUnfold : 用来表示本层级的展开和闭合状态 isCanUnfold : 用于表示本层级是否能够展开, 只有当 subs 属性的个数不为0时, 才取值 YES index : 表示当前的层级, 第一层的值为0

#import <Foundation/Foundation.h>

@interface LTMenuItem : NSObject
/** 名字 */
@property (nonatomic, strong) NSString *name;
/** 子层 */
@property (nonatomic, strong) NSArray<LTMenuItem *> *subs;

#pragma mark - < 辅助属性 >
/** 是否选中 */
@property (nonatomic, assign) BOOL isSelected;
/** 是否展开 */
@property (nonatomic, assign) BOOL isUnfold;
/** 是否能展开 */
@property (nonatomic, assign) BOOL isCanUnfold;
/** 当前层级 */
@property (nonatomic, assign) NSInteger index;
@end

#import "LTMenuItem.h"

@implementation LTMenuItem

/**
 指定subs数组中存放LTMenuItem类型对象
 */
+ (NSDictionary *)mj_objectClassInArray
{
  return @{@"subs" : [LTMenuItem class]};
}

/**
 判断是否能够展开, 当subs中有数据时才能展开
 */
- (BOOL)isCanUnfold
{
  return self.subs.count > 0;
}
@end

第四步, 设置展开闭合时, 需要显示的数据

在控制器 LTMenuItemViewController 中, 当前展示的数据是数组 menuItems , 此时并不好控制应该展示在 tableView 中的数据, 所以添加一个新的属性, 用来包含需要展示的数据


@interface LTMenuItemViewController () 
/** 菜单项 */
@property (nonatomic, strong) NSMutableArray<LTMenuItem *> *menuItems;
/** 当前需要展示的数据 */
@property (nonatomic, strong) NSMutableArray<LTMenuItem *> *latestShowMenuItems;
@end

其中 latestShowMenuItems 就是展示在tableView中的数据

使用懒加载, 创建 latestShowMenuItems


- (NSMutableArray<LTMenuItem *> *)latestShowMenuItems
{
  if (!_latestShowMenuItems) {
    self.latestShowMenuItems = [[NSMutableArray alloc] init];
  }
  return _latestShowMenuItems;
}

修改数据源方法, 使用 latestShowMenuItems 替换 menuItems


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  return self.latestShowMenuItems.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  LTMenuItemCell *cell = [tableView dequeueReusableCellWithIdentifier:LTMenuItemId forIndexPath:indexPath];
  cell.menuItem = self.latestShowMenuItems[indexPath.row];
  return cell;
}