我想在 Collection View 单元格中插入三张图片,3 张图片。每个单元格一张图像。只有一个部分。 但是当模拟器显示黑屏时,没有任何图像。 这是我的部分代码:
import Foundation
import UIKit
class CatImagesViewController:UIViewController,UICollectionViewDataSource,UICollectionViewDelegate
{
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let con = CatService(test:"test")
let temp = NSUserDefaults()
let number = temp.integerForKey("num_of_images")
var title_array:Array<String> = con.imageNamesForCategoryAtIndex(number)
var string:String = title_array[indexPath.row]
print("indexPath.row \(indexPath.row)");
print("string is \(string)")
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("firstCollectionCell", forIndexPath: indexPath)
let imageview:UIImageView=UIImageView(frame: CGRectMake(50, 50, self.view.frame.width-200, 50))
let image:UIImage = UIImage(named:string)!
imageview.image = image
// self.view.addSubview(imageview)
cell.contentView.addSubview(imageview)
return cell
}
}
修改了cell.contentView.addSubview(image view)
,还是黑屏
最佳答案
你应该使用
cell.contentView.addSubview(imageview)
indexPath.row 用于获知单元格在表格中的位置。
设置高度:
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSizeMake(50, 414)
}
你应该使用 NSIndexPath 的属性项
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let con = CatService(test:"test")
let temp = NSUserDefaults()
let number = temp.integerForKey("num_of_images")
var title_array:Array<String> = con.imageNamesForCategoryAtIndex(number)
var string:String = title_array[indexPath.item]
print("indexPath.row \(indexPath.item)");
print("string is \(string)")
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("firstCollectionCell", forIndexPath: indexPath)
let imageview:UIImageView=UIImageView(frame: CGRectMake(50, 0, self.view.frame.width-200, 50))
let image:UIImage = UIImage(named:string)!
imageview.image = image
cell.contentView.addSubview(imageview)
return cell
}
关于ios - 如何在 Collection View 单元格中插入图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33334692/