用swift写一下用uicollectionview显示九宫格的代码
时间: 2023-06-05 09:05:05 浏览: 200
以下是用 Swift 编写的 UICollectionView 显示九宫格的代码:
首先,在 ViewController.swift 中添加以下代码:
```
import UIKit
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
let reuseIdentifier = "cell"
let items = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
override func viewDidLoad() {
super.viewDidLoad()
let layout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
layout.minimumLineSpacing = 10
layout.minimumInteritemSpacing = 10
layout.itemSize = CGSize(width: (view.frame.size.width - 30)/3, height: (view.frame.size.width - 30)/3)
let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height), collectionViewLayout: layout)
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
collectionView.backgroundColor = UIColor.white
collectionView.dataSource = self
collectionView.delegate = self
view.addSubview(collectionView)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
cell.backgroundColor = UIColor.blue
let label = UILabel(frame: CGRect(x: 0, y: 0, width: cell.frame.size.width, height: cell.frame.size.height))
label.textAlignment = .center
label.text = items[indexPath.row]
label.textColor = UIColor.white
cell.contentView.addSubview(label)
return cell
}
}
```
代码解释:
- `UICollectionViewFlowLayout` 是集合视图的布局对象,用于设置集合视图的外观和布局。
- `UICollectionView` 是集合视图的视图对象,用于显示 客户端 端的 IU。我们注册了 UITableViewCell,在 cellForItemAt 方法中添加了数字标签,然后返回 UITableViewCell。
最后,我们运行代码,就可以看到一个显示九宫格的集合视图。