bea*_*one 4 ios swift ios-autolayout
I want to insert three images in collection view cell, 3 images. One image for each cell.Only one section. But when the simulator shows black screen, no any images. Here is part of my code:
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
}
}
Run Code Online (Sandbox Code Playgroud)
I revised cell.contentView.addSubview(image view), but still black screen.
You should use
cell.contentView.addSubview(imageview)
Run Code Online (Sandbox Code Playgroud)
indexPath.row is used to know the cell position in the table.
To set the height:
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSizeMake(50, 414)
}
Run Code Online (Sandbox Code Playgroud)
And you should use the property item of 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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20912 次 |
| 最近记录: |