Uicollectionview Adding Image to a Cell

how to insert images in collection view cell

You should use

cell.contentView.addSubview(imageview)

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)
}

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
}

UICollectionView adding image to a cell

First of all, the way you add images in your cell is pretty dangerous. The reason is that your cells are being reused (for exemple when you scroll, or when you reloadData), and these images are never removed on reuse. So you will start seing them everywhere, and you can even get to the point where your cell contains multiple occurrences of the image. Here are two ways to do it :

  • First way (the good way) : You subclass your UICollectionViewCell, and give the subclass an "imageView" property. Then you do this in your CustomCollectionViewCell.m file :

    // Lazy loading of the imageView
    - (UIImageView *) imageView
    {
    if (!_imageView) {
    _imageView = [[UIImageView alloc] initWithFrame:self.contentView.bounds];
    [self.contentView addSubview:_imageView];
    }
    return _imageView;
    }

    // Here we remove all the custom stuff that we added to our subclassed cell
    -(void)prepareForReuse
    {
    [super prepareForReuse];

    [self.imageView removeFromSuperview];
    self.imageView = nil;
    }

    Then in your ViewController your have to declare the new class of your collectionViewCells like this :

    [self.collectionView registerClass:[CustomCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];

    It will ensure that the images are correctly removed on reuse, plus it's way easier to setup the cell in your collectionView delegate.

  • Second way (The dirty way), you remove the views every time you load a new cell :

    - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView                 cellForItemAtIndexPath:(NSIndexPath *)indexPath
    {
    for (UIView *subview in [cell.contentView subviews]) {
    [subview removeFromSuperview];
    }

    if (question.picture != (id)[NSNull null]) {
    //add AsyncImageView to cell
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.clipsToBounds = YES;
    imageView.tag = IMAGE_VIEW_TAG;
    [cell.contentView addSubview:imageView];
    [[AsyncImageLoader sharedLoader] cancelLoadingImagesForTarget:imageView];
    imageView.imageURL = [NSURL URLWithString:question.picture];
    }
    }

    This way is far easier but i wouldn't recommend it :P

Now try this and let me know how your bug evolves.

UICollectionView adding image and button

This is the solution for the issue I mentioned above, I think it might be helpful for others, so positing the code here

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collectionCell" forIndexPath:indexPath];
if(indexPath.row>0)
[self.cameraRoll thumbAtIndex:(indexPath.row-1) completionHandler:^(UIImage *thumb) {
UIImageView *imageView = [[UIImageView alloc] initWithImage:thumb];
imageView.frame = CGRectMake(0,0,cell.frame.size.width, cell.frame.size.height);
imageView.contentMode = UIViewContentModeScaleAspectFill;
[cell.contentView addSubview:imageView];
}];
else{
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"btn_take_pic.png"]];
imageView.frame = CGRectMake(0,0,cell.frame.size.width, cell.frame.size.height);
imageView.contentMode = UIViewContentModeScaleAspectFill;
[cell.contentView addSubview:imageView];
}
return cell;
}

How to show three rounded images in Collectionview cell in all iPhone screen sizes in swift

In your collectionview cell Set constraints as shown in attached image, i.e. ur image view width should depend on imageview height, you can do it using ratio. Sample Image

Then in willDisplay method calculate cornerRadius

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath)
{
guard let cell = cell as? TestCollectionViewCell else
{
return
}

let cellHeight : CGFloat = cell.frame.size.height
let labelHeight : CGFloat = cell.label?.frame.size.height ?? 0.0
cell.imageView?.layer.cornerRadius = (cellHeight - labelHeight) / 2.0
}

Sample Image

Sample Image

Sample Image

Below is the entire code

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout

{

@IBOutlet weak var collectionView : UICollectionView? = nil
let horizontalSpaceBetweenCell : CGFloat = 16
let verticalSpaceBetweenCell : CGFloat = 16
let edgeInsets = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)

override func viewDidLoad()
{
super.viewDidLoad()
setup()
}

func setup()
{
let nib = UINib(nibName: "TestCollectionViewCell", bundle: nil)
collectionView?.register(nib, forCellWithReuseIdentifier: "TestCollectionViewCell")
}

func numberOfSections(in collectionView: UICollectionView) -> Int
{
return 1
}


func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return 40
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TestCollectionViewCell", for: indexPath) as? TestCollectionViewCell
{
return cell
}

return UICollectionViewCell()
}

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath)
{
guard let cell = cell as? TestCollectionViewCell else
{
return
}

let cellHeight : CGFloat = cell.frame.size.height
let labelHeight : CGFloat = cell.label?.frame.size.height ?? 0.0
cell.imageView?.layer.cornerRadius = (cellHeight - labelHeight) / 2.0
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
let numberOfCellsPerRow = 3
let otherSpace = (edgeInsets.left + edgeInsets.right)
let width = (collectionView.frame.size.width - otherSpace) / CGFloat(numberOfCellsPerRow)
return CGSize(width: width, height: 80) // Height can be anything 80, 90 ,100
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 16
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return edgeInsets
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
{

}

}

How do I change the Image of only 1 button in Collection View and make all other button Images different in Swift

have a variable on your collectionView ViewController that has the songPlaying: Int? and then in your cellForItemAt function you can check if indexPath.row == songPlaying show play else show pause. Have clicking on the button change the songPlaying to that tag and reload your collectionView. I am not sure where your conditions func is being used, but that seems unnecessary you should just have a buttonImage variable on the cell and set it in the cellForItemAt.



Related Topics



Leave a reply



Submit