swift storyboard创建九宫格完整步骤和代码
时间: 2024-03-10 17:46:40 浏览: 18
创建九宫格的步骤如下:
1. 创建一个新的 Xcode 项目,选择 Single View Application。
2. 在 Main.storyboard 中添加一个 UICollectionView。在 Attributes Inspector 中将 Scroll Direction 设置为 Vertical。
3. 在 UICollectionViewCell 中添加一个 UILabel,将其居中,并设置它的控制点约束(Control Point Constraints)为 0。
4. 在 Attributes Inspector 中将 Cell Size 设置为 100 x 100,Minimum Spacing 设置为 0。
5. 在 ViewController.swift 中添加以下代码:
```
import UIKit
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
@IBOutlet weak var collectionView: UICollectionView!
let items = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = self
collectionView.delegate = self
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CustomCell
cell.label.text = items[indexPath.row]
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("You selected cell #\(indexPath.item + 1)")
}
}
class CustomCell: UICollectionViewCell {
@IBOutlet weak var label: UILabel!
}
```
6. 在 Main.storyboard 中选择 UICollectionViewCell,将其 Class 设置为 CustomCell,并将 Identifier 设置为 cell。
这样,你就可以在模拟器中运行你的应用程序,看到一个九宫格了。