Create 3x3 array using Imageviews - SWIFT

Asked

Viewed 355 times

1

How do I programmatically create a 3x3 matrix composed of 9 Imageviews ?

  • 1

    Have you ever tried to simply declare it: var anArray:[[ImageView]] and to initialize something like self.anArray = [[iv1, iv2, iv3], [iv4, iv5, iv6], [iv7, iv8, iv9]]?

  • After all, I want to build a square with nine squares inside. Each square will receive an image that will have a specific order. ?

2 answers

0


The @carlosfigueira comment answers your question:

var matriz: [[UIImageView]] = [[UIImageView(), UIImageView(), UIImageView()],
    [UIImageView(), UIImageView(), UIImageView()],
    [UIImageView(), UIImageView(), UIImageView()]]

matriz[1][1] //<UIImageView: 0x7fca39d34520; frame = (0 0; 0 0); userInteractionEnabled = NO; layer = <CALayer: 0x7fca39d33a70>>
  • I have 9 images in the project and I want to play them in this matrix, each image will be inside an image view, in the same order from 1 to 9. ?

  • you can use the class initialization method public init(frame: CGRect). In the example above it would be: var matriz: [[UIImageView]] = [[UIImageView(frame: CGRectMake(0, 0, 100, 100)), UIImageView(frame: CGRectMake(0, 0, 50, 50)), ...

0

Have you considered using a Uicollectionview? Collection view would set the frames of the cells where the images appear, even if the images have different dimensions. Take a look at the code below, which creates an array of 9 images and shows how you would access this array in Collection view protocols.

import UIKit
var arrayDeImagens = [UIImage]()
// só para criar as imagens fake
for _ in 1...9 {
    arrayDeImagens.append(UIImage())
}

// MARK: UICollectionViewDataSource

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return arrayDeImagens.count
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    let imagem = arrayDeImagens[indexPath.item]

    /* aqui tu vais instanciar tua subclasse de UICollectionViewCell
       que contém uma UIImageView como subview e ira renderizar a tua imagem */

    return UICollectionViewCell() // essa linha é só para o compilador ficar quieto
}

// MARK: UICollectionViewDelegateFlowLayout

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    return arrayDeImagens[indexPath.item].size
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.