swift: Same image used in different UIImageView? - ios

I have done the following to assign an UIImage to different instance of UIView object. Inside my UIView, I have an UIImageView which holds the Image.
var transitionImageNames = ["1.png", "2.png", "3.png", "4.png"]
var count=0
for item in myList {
var transitionImageName = transitionImageNames[count]
item.transitionImageView.image = UIImage(named: transitionImageName)
// transitionImageName refers to 4 different images, let say 1,2,3,4.png
if (count<=3) {
count += 1
}
}
there are a number of different items in myList. I have printed out the item instance, all of them have different instance value. However, I found that for the transitionImageView to be displayed, even if I set 1, 2, 3, 4.png to 4 different items in the myList, they all display the same image (which is the last one set)
Any idea on why?

I think you need something like this:
var transitionImageNames = ["1.png", "2.png", "3.png", "4.png"]
for (index, item) in myList.enumerated() {
item.transitionImageView.image = UIImage(named: transitionImageNames[index])
}

Related

Adding Bool values to every element of matrix array (two dimensional array) in Swift

I have a 2D array that represents every coordinate of a maze:
var maze:[[Int]]
let column = [Int](repeating: 0, count: y)
self.maze = ([[Int]](repeating: column, count: x))
I need to assign 4 Bool values to every single coordinate:
canMoveUp = false
canMoveDown = false
canMoveLeft = false
canMoveRight = false
The problem is I already have a lot of code written using maze:[[Int]]. Is there a way of creating an extra object reaching maze[[Int]] and adding bool values to its every element not affecting the original maze var? If not: just an example of declaring 2D array with Bool values for every element would be really helpful.
I am at the very beginning of my developer career, please be indulgent. Any help is much appreciated!
Is there a way of creating an extra object reaching maze[[Int]] and adding bool values to its every element not affecting the original maze var?
No. Int is a fundamental type, not something you can extend.
You could create a second maze array with the new data in the corresponding locations, but that's a terrible idea; trying to keep two data structures in sync at all times is always an exercise in pain.
What you should do is to refactor your code so that you're using an appropriate type for your maze data instead of the single Int that you're using now. If you do it right, you'll only need to do it once, and from then on you can add new data to each cell in the maze with much less effort. Create a data structure that contains everything that you currently need, like:
struct MazeElement {
var up = false
var down = false
var left = false
var right = false
var count = 0
}
let columns = 4
let rows = 3
var maze = [[MazeElement]](repeating: [MazeElement](repeating:MazeElement(), count: rows), count: columns)
Next you'll have find all the places in your code where you expect maze to be a 2D array of Int, and change each one so that it expects a MazeElement instead. In practice, that mostly means that lines like:
let foo = maze[i][j]
need to be changed to:
let foo = maze[i][j].count
But the benefit is that now it's easy to also get the directional information for each cell:
let canMoveUp = maze[i][j].up
let canMoveLeft = maze[i][j].left
Better yet, when you decide to add some new data to each element, you won't have to do all that work all over again... just change the definition of MazeElement to include the new data:
struct MazeElement {
var up = false
var down = false
var left = false
var right = false
var count = 0
var color = UIColor.white
}

UILabels within an array not showing up on ViewController

So I'm trying to make a grid/table show up in my app, and to do this I created an array of UILabels with:
var rows = 2
var columns = 2
var grid = [[UILabel]](count: rows, repeatedValue: [UILabel](count: columns, repeatedValue: UILabel()))
then I created each UILabel with:
for i in 0 ..< grid.count
{
for j in 0 ..< grid[0].count
{
grid[i][j].frame = CGRectMake(x + CGFloat(j*Int(gridSpace)), y + CGFloat(i*Int(gridSpace)), gridSpace, gridSpace)
grid[i][j].backgroundColor = UIColor.redColor()
grid[i][j].hidden = false
grid[i][j].textColor = UIColor.whiteColor()
grid[i][j].textAlignment = NSTextAlignment.Center
grid[i][j].text = "label: [\(i)][\(j)]"
self.view.addSubview(grid[i][j])
print("grid[\(i)][\(j)]X = \(grid[i][j].frame.origin.x) grid[\(i)][\(j)]Y = \(grid[i][j].frame.origin.y)")
}
}
What happens is actually pretty interesting. The code compiles and everything, but only one of the labels shows up. The dimensions and everything about the label are perfect, but only one of them shows up.
The label that shows up is always the grid[rows-1][columns-1] label. But when I print the x and y coordinates of the rest of the labels that are supposed to be in the grid array, all of the coordinates are exactly where they are supposed to be on the viewcontroller it's just that the labels don't show up. when I changed the for loop to
for i in 0 ..< grid.count-1
{
for j in 0 ..< grid[0].count-1
{
still only the last label (the grid[rows-1][columns-1] label) shows up yet the coordinates are exactly where they should be. Another weird thing is that if I change the line
grid[i][j].text = "test label: [\(i)][\(j)]"
to
if(j != grid[0].count-1)
{
grid[i][j].text = "test label: [\(i)][\(j)]"
}
then the label that shows up still has the coordinates of the grid[rows-1][columns-1] but has the labeltext of grid[rows-1][columns-2]
Can anyone fix my problem for me or explain whats going on?
It's because of the way that you have initialized your grid with repeated values. If the repeated value is of reference type, the array will actually create only one item and point all indexes to that item, so in your for loops you're changing the frame for the one and only UILabel over and over again. thats why you only see the last one on your screen.
To create the array you want replace this:
var grid = [[UILabel]](count: rows, repeatedValue: [UILabel](count: columns, repeatedValue: UILabel()))
with
var grid = [[UILabel]]()
for row in 0..<rows {
grid.append([UILabel]())
for column in 0..<columns{
grid[row].append(UILabel())
}
}
or
var grid = [[UILabel]]((0..<rows).map { _ in
[UILabel]((0..<columns).map { _ in
UILabel()
})
})

How to return number of views(ZLSwipeableViewSwif) like UITableview data source?

I am trying to implement , i cannot set number of views, i want to set only five view, which property i need to use before view is loading.
Library link enter link description here
self.swipeableView.numberOfActiveView = 5;
self.swipeableView.discardViews()
self.swipeableView.loadViews()
I am trying with their demo application.
You can Replace your colors array with other array like,
Declare one more array below that color array,
var imgArray = ["1","2","3","4"]
Now find the color array from the view did load and replace it with imgArray like,
swipeableView.nextView = {
if self.colorIndex < self.imgArray.count //self.colors.count
{
var cardFrame = CGRectMake(self.swipeableView.frame.origin.x, 0, self.swipeableView.frame.size.width, 250)
var cardView = CardView(frame: cardFrame)
var img : UIImageView = UIImageView(frame: cardView.bounds)
img.image = UIImage(named: self.imgArray[self.colorIndex])
cardView.addSubview(img)
self.colorIndex++
....
....
}
This working fine at my end so hope this will help you.

Random images to (many) Image Views

Sadly, I've got 36 UIImages and need to set a random image to each one.
My 6 images are named;
"Owl1"
"Owl2"
"Owl3"
"Owl4"
"Owl5"
"Owl6"
So, I want to set one random image to my 36 different UIImages. What is the best way to do this? An array? Here's my "try" so far.
var images: [UIImage] = [
UIImage(named: "Owl1")!,
UIImage(named: "Owl2")!,
UIImage(named: "Owl3")!,
UIImage(named: "Owl4")!,
UIImage(named: "Owl5")!,
UIImage(named: "Owl6")!
]
var randomUIImage = [Image1, Image2, Image3, Image4, Image5...]
randomUIImage.shuffleInPlace()
randomUIImage[0].image = images[0]
randomUIImage[1].image = images[1]
But I realized this will not work, and I can't make this code for all 36 images... Anyone got a better idea? ;-)
Tip: you can use a range + map to create an array of your images.
let images = (1...6).map { UIImage(named: "Owl\($0)") }
(1...6) produces a collection of Ints, from 1 to 6 (including 6), and with map we create a new instance of UIImage for each Int, using them for the naming - since you named your images in order, it's convenient. It's like doing a loop and appending a new intance of UIImage to an array inside the loop, using an index for the naming: "Owl1", "Owl2", etc.
If you also have your UIImageViews in an array, you can assign the images with a loop.
Here's an example (I didn't verify on Xcode but it should be close to what you need):
for view in imageViewsArray { // the array with the 36 imageViews
// a random index for the array of 6 images
let randomIndex = Int(arc4random_uniform(UInt32(images.count))
// assign the randomly chosen image to the image view
view.image = images[randomIndex]
}
You can have an array of image names, and an array of images to hold them..
var imageNames:[String] = ["Owl1", "Owl2"....etc]
var owlImages:[UIImage] = []
Then randomly append the images
for index in 0...imageNames.count - 1 {
var randomInt = Int(arc4random_uniform(UInt32(imageNames.count)) //a random int from 0 to the size of your array
owlImages.append(UIImage(named: imageNames[randomInt] //add the random image to the array
}

need to random an array of images and words. Arc4random_uniform

I'm working on a project of shapes and words. I currently have two arrays. One array is of images, the other array is just a set of strings that describes the first array of images. I'm using 4 buttons to display 4 items in the "string" array. Can someone please tell me how can I utilize arc4random but also make sure one of my 4 buttons display the name of the image.
Below is a quick example of my arrays
var myShapes = ["circle", "square", "rectangle"]
var images = ["circle.png", "square.png", "rectangle.png"]
How do I utilize arc4Random but make sure one item from each array always equals each other?
Adding information for the function to randomize my images.
func randomImage() -> UIImage {
let arrayCount = UInt32(myImages.count)
let unsignedRandomNumber = arc4random_uniform(arrayCount)
let randomNumber = Int(unsignedRandomNumber)
return UIImage(named: myImages[randomNumber])!
}
Below is how I'm doing the random text
let randomDisplayText = buttonDisplayText[Int(arc4random_uniform(UInt32(buttonDisplayText.count)))]

Resources