「OC」初识MVC —— 简单学习UITableView的解耦

2024-08-31 02:36

本文主要是介绍「OC」初识MVC —— 简单学习UITableView的解耦,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

「OC」初识MVC —— 简单学习UITableView的解耦

文章目录

  • 「OC」初识MVC —— 简单学习UITableView的解耦
    • 写在前面
    • 认识MVC
    • 解耦
      • 数据源
      • 代理
    • 创建cell的基础类
    • 创建section的相关类
    • 分离数据源
    • 分离代理
    • 总结
    • 参考资料

写在前面

最近在学习了解MVC,然后开始发现,原来之前自己写的内容,真的拿不上一点台面,真是叫人头大啊。好吧😭,知耻而后勇,只能继续好好学习了。由于是刚刚接触MVC,很多内容都是根据网上内容进行相关学习,因为没有基础的概念认知,如果有错误敬请斧正。

认识MVC

在讨论解耦之前,我们要弄明白 MVC 的核心:控制器(以下简称 C)负责模型(以下简称 M)和视图(以下简称 V)的交互。

这里所说的 M,通常不是一个单独的类,很多情况下它是由多个类构成的一个层。最上层的通常是以 Model 结尾的类,它直接被 C 持有。Model 类还可以持有两个对象:

  1. Item:它是实际存储数据的对象。它可以理解为一个字典,和 V 中的属性一一对应
  2. Cache:它可以缓存自己的 Item(如果有很多)

解耦

我们先前在使用tableView的时候,往往使用以下代码去设置代理源和数据源

self.tableView.delegate = self;
self.tableView.dataSource = self;

数据源

UITableViewDataSource这之中,我们必须实现的有以下的方法

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;

其他可选的内容如下

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView; // 默认情况下如果没有实现,就是1
- (nullable NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section; // 字体样式是固定的。如果你想使用不同的样式,可以使用自定义视图(UILabel)
- (nullable NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section; // 编辑
// 单独的行可以选择不设置为可编辑。如果没有实现,所有行都假定为可编辑。
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath;// 移动/重新排序
// 允许为特定的行选择性显示重新排序的辅助视图。默认情况下,只有在数据源实现了 tableView:moveRowAtIndexPath:toIndexPath: 方法时,重新排序控件才会显示。
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath;// 索引
- (nullable NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView; // 返回要在节索引视图中显示的节标题列表(例如 "ABCD...Z#")
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index; // 告诉表格哪个节对应于节标题/索引(例如 "B",1)// 数据操作 - 插入和删除支持
// 当行调用了减号或加号按钮(基于单元格的 UITableViewCellEditingStyle)后,数据源必须提交更改
// 对于使用 UITableViewRowAction 的编辑操作不调用 - 将调用动作的处理程序
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath;// 数据操作 - 重新排序/移动支持
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath;

代理

代理主要涉及以下几个方面的内容:

  1. cell、headerView 等展示前、后的回调。
  2. cell、headerView 等的高度,点击事件。

这样就有一个问题,就是我们需要在创建每一个tableView的时候,我们实现的内容有很大一部分是重复的内容,我们每次都需要为tableView写关于这个代理和数据源的方法代码,这显然是不符合解耦规则的,而且在这个设置代理源和数据源的时候,代码像是V(即tableView)去持有M(即数据源)和C(代理对象),好似也不太符合MVC的规则,我们可以尝试着将数据源和代理进行分离。

创建cell的基础类

因为每个cell的内容其实都大差不差,所以我们可以使用一个单独的类对cell进行分装成Model,方便我们进行初始化,如果我们遇到特殊需求的cell那么其实我们只要再在分装好的item之中写一个扩展,添加需要的属性即可

// JCUITableViewItems.h
#import <Foundation/Foundation.h>
#import "UIKit/UIKit.h"
NS_ASSUME_NONNULL_BEGIN@interface JCUITableViewItems : NSObject@property (copy, nonatomic) NSString *identifier;
@property (nonatomic, strong) UIImageView *customImageView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *subtitleLabel;
@property (nonatomic, strong) UIImageView *iconView;-(instancetype)initWithImage: (UIImage*)image title:(NSString*)title subtitle:(NSString*)subtitle;
@endNS_ASSUME_NONNULL_END// JCUITableViewItems.m
#import "JCUITableViewItems.h"@implementation JCUITableViewItems- (instancetype)initWithImage:(UIImage *)image title:(NSString *)title subtitle:(NSString *)subtitle {self = [super init];if (self) {self.ID = [[NSUUID UUID] UUIDString];self.customImageView = [[UIImageView alloc] initWithImage:image];self.titleLabel = [[UILabel alloc] init];self.titleLabel.text = title;self.subtitleLabel = [[UILabel alloc] init];self.subtitleLabel.text = subtitle;self.iconView = [[UIImageView alloc] init];}return self;
}@end

创建section的相关类

和上面一样,其实我们也可以将section设置成为一个类去分装section

但是这样存在一个问题,就是我们的代理和数据源,分别代表着MVC当中的V和M,这样设置使得V持有了M和C,而实际上我们需要的是让C去持有M和V。为了减少在控制器之中的代码量以及使得UITableView的设计更加合理,我们需要想办法来解决这些问题。

// JCSectionObject.h
#import <Foundation/Foundation.h>
#import "UIKit/UIKit.h"
NS_ASSUME_NONNULL_BEGIN
@class JCUITableViewItems;
@interface JCSectionObject : NSObject@property (copy,nonatomic) NSString *headerTitle;
@property (copy,nonatomic) NSString *footerTitle;@property (nonatomic, strong) NSMutableArray<JCUITableViewItems *> *items;-(instancetype)initWithArray:(NSMutableArray*) items headerTitle: (NSString*) header footerTitle : (NSString *)footer;@endNS_ASSUME_NONNULL_END// JCSectionObject.m
#import "JCSectionObject.h"@implementation JCSectionObject-(instancetype)initWithArray:(NSMutableArray*) items headerTitle: (NSString*) header footerTitle : (NSString *)footer {self = [super init];if (self) {_headerTitle = header;_footerTitle = footer;_items = items;}return self;
}- (void)addItem:(JCUITableViewItems *)item {[self.items addObject:item];
}@end

分离数据源

我们为了避免重复内容的出现,我们可以将数据源直接分装成为一个类

//JCTableViewDataSource.h
#import <Foundation/Foundation.h>
#import "UIKit/UIKit.h"
@class JCSectionObject;
NS_ASSUME_NONNULL_BEGIN@interface JCTableViewDataSource : NSObject<UITableViewDataSource>@property (nonatomic, strong) NSMutableArray<JCSectionObject *> *sections;- (void)addSection:(JCSectionObject *)section;@endNS_ASSUME_NONNULL_END//JCTableViewDataSource.m
#import "JCTableViewDataSource.h"
#import "JCUITableViewItems.h"
#import "JCSectionObject.h"
@implementation JCTableViewDataSource- (instancetype)init {self = [super init];if (self) {_sections = [NSMutableArray array];}return self;
}- (void)addSection:(JCSectionObject *)section {[self.sections addObject:section];
}#pragma mark - UITableViewDataSource- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {return self.sections.count;
}- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {return self.sections[section].items.count;
}- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {JCUITableViewItems *item = self.sections[indexPath.section].items[indexPath.row];UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:item.identifier];if (!cell) {cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:item.identifier];}cell.imageView.image = item.customImageView.image;cell.textLabel.text = item.titleLabel.text;cell.detailTextLabel.text = item.subtitleLabel.text;return cell;
}- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {return self.sections[section].headerTitle;
}
- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {return self.sections[section].footerTitle;
}
@end

分离代理

与分离数据源相似,我们也需要对代理之中的内容进行分离,代理之中比较重要的内容就是选中cell,我们需要定义一个block,在代理类之中获取点击的index,然后在控制器之中回调出我们需要的进行的操作

//JCUITableViewDelegate.h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN@interface JCUITableViewDelegate : NSObject<UITableViewDelegate>
@property (nonatomic, copy) void (^didSelectRowAtIndexPath)(NSIndexPath *indexPath);
@endNS_ASSUME_NONNULL_END//JCUITableViewDelegate.m
#import "JCUITableViewDelegate.h"@implementation JCUITableViewDelegate- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {if (self.didSelectRowAtIndexPath) {self.didSelectRowAtIndexPath(indexPath);//将参数传入}
}- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {return 60;
}@end

经过这样的操作,我们就给控制器实现了简单的瘦身,控制器代码如下,我们做了这样的操作,不仅避免了我们先前在添加headertitle需要进行判断,更加方便且易于维护。

#import "ViewController.h"
#import "JCUITableViewItems.h"
#import "JCSectionObject.h"
#import "JCTableViewDataSource.h"
#import "JCUITableViewDelegate.h"
@interface ViewController ()@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) JCTableViewDataSource *dataSource;
@property (nonatomic, strong) JCUITableViewDelegate *delegate;@end@implementation ViewController- (void)viewDidLoad {[super viewDidLoad];self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];[self.view addSubview:self.tableView];self.dataSource = [[JCTableViewDataSource alloc] init];self.delegate = [[JCUITableViewDelegate alloc] init];self.delegate.didSelectRowAtIndexPath = ^(NSIndexPath *indexPath) {NSLog(@"选择了: %@", indexPath);};//通过回调使得index信息能被传回self.tableView.dataSource = self.dataSource;self.tableView.delegate = self.delegate;[self addTestData];[self.tableView reloadData];
}- (void)addTestData {NSMutableArray *section1Items = [NSMutableArray array];JCUITableViewItems *item1 = [[JCUITableViewItems alloc] initWithImage:[UIImage imageNamed:@"image1"] title:@"Title 1" subtitle:@"Subtitle 1"];JCUITableViewItems *item2 = [[JCUITableViewItems alloc] initWithImage:[UIImage imageNamed:@"image1"] title:@"Title 2" subtitle:@"Subtitle 2"];item1.identifier = @"Cell1";[section1Items addObject:item1];[section1Items addObject:item2];JCSectionObject *section1 = [[JCSectionObject alloc] initWithArray:section1ItemsheaderTitle:@"Section 1 Header"footerTitle:@"Section 1 Footer"];NSMutableArray *section2Items = [NSMutableArray array];JCUITableViewItems *item3 = [[JCUITableViewItems alloc] initWithImage:[UIImage imageNamed:@"image2"] title:@"Title 3" subtitle:@"Subtitle 3"];item2.identifier = @"Cell2";[section2Items addObject:item3];JCSectionObject *section2 = [[JCSectionObject alloc] initWithArray:section2ItemsheaderTitle:@"Section 2 Header"footerTitle:@"Section 2 Footer"];[self.dataSource addSection:section1];[self.dataSource addSection:section2];
}@end

这样子我们就获得了以下的UITableView

image-20240828121956952

总结

关于tableView的解耦自我感觉还是一知半解,关于MVC和解耦的思想还是不太理解,对于在解耦的tableView之中使用自定义cell的部分还有一定的不理解,但是还是汇总为了博客记录一下学习的内容,后面还有根据网络申请进行分装,那就在后面学到了相关内容再进行深入学习。

参考资料

如何写好一个UITableView

UITableView 解耦

这篇关于「OC」初识MVC —— 简单学习UITableView的解耦的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1122643

相关文章

使用Python开发一个简单的本地图片服务器

《使用Python开发一个简单的本地图片服务器》本文介绍了如何结合wxPython构建的图形用户界面GUI和Python内建的Web服务器功能,在本地网络中搭建一个私人的,即开即用的网页相册,文中的示... 目录项目目标核心技术栈代码深度解析完整代码工作流程主要功能与优势潜在改进与思考运行结果总结你是否曾经

Mysql表的简单操作(基本技能)

《Mysql表的简单操作(基本技能)》在数据库中,表的操作主要包括表的创建、查看、修改、删除等,了解如何操作这些表是数据库管理和开发的基本技能,本文给大家介绍Mysql表的简单操作,感兴趣的朋友一起看... 目录3.1 创建表 3.2 查看表结构3.3 修改表3.4 实践案例:修改表在数据库中,表的操作主要

springboot简单集成Security配置的教程

《springboot简单集成Security配置的教程》:本文主要介绍springboot简单集成Security配置的教程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,... 目录集成Security安全框架引入依赖编写配置类WebSecurityConfig(自定义资源权限规则

如何解决Spring MVC中响应乱码问题

《如何解决SpringMVC中响应乱码问题》:本文主要介绍如何解决SpringMVC中响应乱码问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Spring MVC最新响应中乱码解决方式以前的解决办法这是比较通用的一种方法总结Spring MVC最新响应中乱码解

如何使用Python实现一个简单的window任务管理器

《如何使用Python实现一个简单的window任务管理器》这篇文章主要为大家详细介绍了如何使用Python实现一个简单的window任务管理器,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起... 任务管理器效果图完整代码import tkinter as tkfrom tkinter i

Spring MVC使用视图解析的问题解读

《SpringMVC使用视图解析的问题解读》:本文主要介绍SpringMVC使用视图解析的问题解读,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Spring MVC使用视图解析1. 会使用视图解析的情况2. 不会使用视图解析的情况总结Spring MVC使用视图

C++中函数模板与类模板的简单使用及区别介绍

《C++中函数模板与类模板的简单使用及区别介绍》这篇文章介绍了C++中的模板机制,包括函数模板和类模板的概念、语法和实际应用,函数模板通过类型参数实现泛型操作,而类模板允许创建可处理多种数据类型的类,... 目录一、函数模板定义语法真实示例二、类模板三、关键区别四、注意事项 ‌在C++中,模板是实现泛型编程

基于@RequestParam注解之Spring MVC参数绑定的利器

《基于@RequestParam注解之SpringMVC参数绑定的利器》:本文主要介绍基于@RequestParam注解之SpringMVC参数绑定的利器,具有很好的参考价值,希望对大家有所帮助... 目录@RequestParam注解:Spring MVC参数绑定的利器什么是@RequestParam?@

使用EasyExcel实现简单的Excel表格解析操作

《使用EasyExcel实现简单的Excel表格解析操作》:本文主要介绍如何使用EasyExcel完成简单的表格解析操作,同时实现了大量数据情况下数据的分次批量入库,并记录每条数据入库的状态,感兴... 目录前言固定模板及表数据格式的解析实现Excel模板内容对应的实体类实现AnalysisEventLis

Java进阶学习之如何开启远程调式

《Java进阶学习之如何开启远程调式》Java开发中的远程调试是一项至关重要的技能,特别是在处理生产环境的问题或者协作开发时,:本文主要介绍Java进阶学习之如何开启远程调式的相关资料,需要的朋友... 目录概述Java远程调试的开启与底层原理开启Java远程调试底层原理JVM参数总结&nbsMbKKXJx