import UIKit
let reuseIdentifier = "MyCell"
class ViewController: UIViewController, UICollectionViewDataSource {
var myimage = UIImage(named: "1433584709_clock_ios7_ios_7")
@IBOutlet weak var collectionView: UICollectionView!
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CollectionViewCell
cell.imageView.image = myimage
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView.collectionViewLayout = CollectionViewLayout()
self.collectionView.registerClass(CollectionViewCell.self, forCellWithReuseIdentifier: "MyCell")
// Do any additional setup after loading the view, typically from a nib.
}
}
我有这个代码添加这么多具有相同图像的单元格。 但是,我想让细胞有不同的图片。 请告诉我怎么做。
答案 0 :(得分:0)
使用图像数组而不是var myImage,因为集合视图或tableview需要某种形式的列表或数组来存储所有项目。 indexPath.row将返回collectionview正在查找的图像的索引。即。
var images: [String] = ["image1", "image2"]
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CollectionViewCell
cell.imageView.image = UIImage(named: self.images[indexPath.row])
return cell
}
同样在功能collectionView:numberOfItemsInSection:
返回self.images.count
这是完整的代码,假设您有一个自定义的CollectionViewCell类
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
@IBOutlet weak var collectionView: UICollectionView!
var images : [String] = ["image1", "image2"]
private let reuseIdentifier = "MyCell"
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView.registerClass(CollectionViewCell.self, forCellWithReuseIdentifier: "MyCell")
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CollectionViewCell
cell.imageView.image = UIImage(named: self.images[indexPath.row])
return cell
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.images.count
}
}
答案 1 :(得分:0)
你的图片来自哪里?
假设我有像myImageArray [] []这样的2D图像数组,然后更改行:
cell.imageView.image = myImage
到
cell.imageView.image = myImageArray[indexPath.section][indexPath.row]