前言:
如何有效地解决系统的耦合性以及达到软件工程的工程性、规范性是一项重要的任务。对于UIKit而言,将数据源、cell子项布局、UICollectionView布局从ViewController里面抽出来是一条可行路。本文将以MVC架构为例,阐述一个较为完善的UICollectionView控件的开发。最终的成品如下图所示:
Model层:
Model层处于架构的最底层,为Controller层提供数据源支持,离开了它,系统要想增添或修改很难。在本文中,Model层提供UILabel及UIImageView的数据源。示例如下:
import Foundation
class ListModel: NSObject{
var labelName: String!
var imageName: String!
init(labelName: String, imageName: String) {
self.labelName = labelName
self.imageName = imageName
}
}
可以看到这里的内容很简单,两个类变量,一个构造器用以初始化。
View层:
View层是用户接触一个系统而言最能直接触碰到的层次。一般而言,教科书处于教学原因大多是把View层放入 Controller层里面,这就造成了Controller过于臃肿、过于耦合的现状。特别是对于UIKit而言,不像Android还有独立的xml文件用于编写界面(StoryBoard用处不如纯代码灵活)。在这里,View层将分为两个部分,一个是cell子项的布局,另一个是UICollectionView的布局,二则均采用SnapKit进行约束。
cell子项的布局如下:
import Foundation
import UIKit
import SnapKit
class ListCell: UICollectionViewCell{
var cellLabel: UILabel!
var cellImageView: UIImageView!
var rootImageView: UIImageView!
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
installRootImageView()
installCellImageView()
installCellLabel()
}
// MARK: - Constraight block for cell widget.
private func installRootImageView(){
rootImageView = UIImageView()
rootImageView.backgroundColor = UIColor.white
rootImageView.layer.cornerRadius = 20
self.addSubview(rootImageView)
rootImageView.snp.makeConstraints{ make in
make.width.equalTo(self.contentView.frame.width - 80)
make.height.equalTo(170)
make.centerX.equalToSuperview()
}
}
private func installCellImageView(){
cellImageView = UIImageView()
cellImageView.tag = 1002
cellImageView.contentMode = .scaleAspectFit
self.rootImageView.addSubview(cellImageView)
cellImageView.snp.makeConstraints{ make in
make.width.height.equalTo(64)
make.left.equalTo(self.rootImageView.snp.left).offset(60)
make.centerY.equalTo(self.rootImageView)
}
}
private func installCellLabel(){
cellLabel = UILabel()
cellLabel.tag = 1001
cellLabel.font = UIFont.systemFont(ofSize: 20)
self.rootImageView.addSubview(cellLabel)
cellLabel.snp.makeConstraints{ make in
make.width.equalTo(70)
make.height.equalTo(35)
make.left.equalTo(self.cellImageView.snp.right).offset(39)
make.centerY.equalTo(self.rootImageView)
}
}
}
这里的代码先是让该类继承于UICollectionViewCell,然后创建类变量控件,接着调用必要的构造器和重写构造器;最后,创建了三个installXXX()
的方法用以初始化控件的基本属性,编写约束。
创建完cell子项的布局还要创建UICollectionView的布局,该布局示例如下:
import Foundation
import UIKit
import SnapKit
class BasicView: UIView{
var listCollectionView: UICollectionView!
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.white
installListCollectionView()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Constraight block for view widget.
private func installListCollectionView(){
let flowLayout = UICollectionViewFlowLayout()
flowLayout.scrollDirection = .vertical
flowLayout.itemSize = CGSize(width: self.frame.width, height: 180)
listCollectionView = UICollectionView(frame: CGRect(x: 0, y: 150, width: self.frame.width, height: self.frame.height), collectionViewLayout: flowLayout)
listCollectionView.backgroundColor = UIColor(red: 0.958, green: 0.958, blue: 0.998, alpha: 1.0)
listCollectionView.register(ListCell.self, forCellWithReuseIdentifier: "TEST_ID")
self.addSubview(listCollectionView)
listCollectionView.snp.makeConstraints{ make in
make.top.equalTo(self.safeAreaLayoutGuide.snp.top)
make.width.equalTo(self.snp.width)
make.height.equalTo(self.snp.height)
}
}
}
这里关于内容结果不再赘述。值得一提的是,每个独立的View(基本控件除外,如UILabel、UIButton等)在新建文件且未加指定颜色时其背景颜色是黑色的,应该将其颜色设置为正常色(例如白色)。
Controller层:
在 Controller层我们不再让VC实现UICollectionViewDataSource这个协议,而是单独独立DataSource到我们的自定义文件中,这是让Controller层解耦的关键。自定义的DataSource内容如下:
import Foundation
import UIKit
class ListDataSource: NSObject, UICollectionViewDataSource{
var dataSource: Array<ListModel>!
// Requied a data source for The class to init.
init(dataSource: Array<ListModel>) {
self.dataSource = dataSource
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
dataSource.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TEST_ID", for: indexPath)
let label = cell.viewWithTag(1001) as? UILabel
label?.text = dataSource[indexPath.row].labelName
let imageView = cell.viewWithTag(1002) as? UIImageView
imageView?.image = UIImage(named: dataSource[indexPath.row].imageName)
return cell
}
}
说明:这里实现了两个必要的方法,数据源是泛型集合。最重要的是,自定义类不仅要实现UICollectionViewDataSource,还要继承于NSObject,否则会报出内部类继承的错误。
最后就是Controller层了,这里已经尽了最大化来解耦,基本上是不可能来减少代码了。示例如下:
import UIKit
class ViewController: UIViewController, UICollectionViewDelegate{
var basicView: BasicView!
var listDataSource: ListDataSource!
var dataSource: Array<ListModel>!
private func initView(){
dataSource = Array<ListModel>()
for _ in 0..<10 {
dataSource.append(ListModel(labelName: "Apple", imageName: "apple"))
}
basicView = BasicView(frame: self.view.frame)
self.view.addSubview(basicView)
listDataSource = ListDataSource(dataSource: dataSource)
basicView.listCollectionView.delegate = self
basicView.listCollectionView.dataSource = self.listDataSource
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.backgroundColor = UIColor(red: 0.958, green: 0.958, blue: 0.998, alpha: 1.0)
initView()
}
}
说明:在这里我们仍然自定义了initView()
方法,从方法名可以猜出,这是个与视图相关的方法,那这个方法是不是也可以解耦呢?答案是否定的,模块和模块、方法和方法之间只能最大化解藕,不能完全解藕,否则模块之间就没有任何联系了。