UITableView
懒加载
lazy var mainView: UITableView = {
let view = UITableView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight - kTopHeight), style: .plain)
view.delegate = self
view.dataSource = self
view.tableHeaderView = UIView()
view.tableFooterView = UIView()
view.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
view.separatorStyle = .none
view.backgroundColor = .white
view.rowHeight = 44
view.showsHorizontalScrollIndicator = false
view.showsVerticalScrollIndicator = false
if
// 底部空余安全距离
view.contentInsetAdjustmentBehavior = .never
view.estimatedRowHeight = 0
view.estimatedSectionHeaderHeight = 0
view.estimatedSectionFooterHeight = 0
} else {
self.automaticallyAdjustsScrollViewInsets = false
}
if
UITableView.appearance().sectionHeaderTopPadding = 0
}
return view
}()
实现代理协议
extension MineViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 30
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")!
cell.textLabel?.text = "测试"
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView .deselectRow(at: indexPath, animated: true)
}
}
添加到视图
self.view.addSubview(self.mainView)
UICollectionView
懒加载
lazy var mainView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.itemSize = CGSize(width: 100, height: 137)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 12
layout.sectionInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
let view = UICollectionView(frame: CGRect(x: 0, y: 57, width: kScreenWidth, height: 137), collectionViewLayout: layout)
view.delegate = self
view.dataSource = self
view.backgroundColor = .white
if
view.contentInsetAdjustmentBehavior = .never
} else {
automaticallyAdjustsScrollViewInsets = false
}
return view
}()
实现代理协议
extension RecXiangYuHaoCell: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: UICollectionViewCell.self), for: indexPath)
cell.contentView.backgroundColor = kRandomColor()
return cell
}
}
添加到视图
addSubview(mainView)
mainView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: String(describing: UICollectionViewCell.self))