swift storyboard可以显示图片的九宫格详细代码
时间: 2024-02-23 18:01:12 浏览: 136
好的,以下是一个使用UICollectionView来实现九宫格图片显示的简单示例代码:
1. 在Storyboard中拖拽一个UICollectionView控件,并设置其约束和相关属性。
2. 创建一个UICollectionViewCell的子类,命名为ImageCell,并在Storyboard中设置其样式和布局。
3. 在ViewController中添加以下代码:
```swift
import UIKit
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
@IBOutlet weak var collectionView: UICollectionView!
let images: [UIImage] = [UIImage(named: "image1")!, UIImage(named: "image2")!, UIImage(named: "image3")!, UIImage(named: "image4")!, UIImage(named: "image5")!, UIImage(named: "image6")!]
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = self
collectionView.delegate = self
}
// MARK: - UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath) as! ImageCell
cell.imageView.image = images[indexPath.row]
return cell
}
// MARK: - UICollectionViewDelegate
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// TODO: 处理选中事件
}
}
```
4. 最后,在ImageCell中添加以下代码:
```swift
import UIKit
class ImageCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
imageView.layer.cornerRadius = 8.0
imageView.layer.masksToBounds = true
}
}
```
这样就可以在UICollectionView中显示九宫格图片了。当然,你可以根据自己的需求对代码进行修改和优化。希望对你有帮助!
阅读全文