Creating a random image generator with Swift - image

I'm trying to make a random image appear on the screen, but I'm new to Swift and am not sure how to do this. I have three images which I want have randomly shown in the image view, when the app is opened.
How do I do this?

Generate a ramdom number from 0 to 2 and show the image by randomly generated number.
var random = arc4random_uniform(3) //returns 0 to 2 randomly
switch random {
case 0:
//show first image
case 1:
//show second image
default:
//show third image
}

If the images are named basically the same thing. For example, "Image1.png, Image2.png, and Image3.png, then you can use this code:
override func viewDidLoad() {
super.viewDidLoad()
ImageView.image = UIImage(named: "Image\(arc4random_uniform(3) + 1).png")
}

imageArr = ["1.jpeg","2.jpeg","3.jpeg","4.jpeg"]
let RandomNumber = Int(arc4random_uniform(UInt32(self.imageArr.count)))
//imageArr is array of images
let image = UIImage.init(named: "\(imageArr[RandomNumber])")
let imageView = UIImageView.init(image: image)

It works for me (Swift 4.2):
let images: [UIImage] = [ #imageLiteral(resourceName: "randomImage1"),
#imageLiteral(resourceName: "randomImage2"),
#imageLiteral(resourceName: "randomImage3")]
let randomImage = images.shuffled().randomElement()

Related

UIScrollView - Duplicate code produces different result

I have a small test project that I'm trying to import into my production project. The ViewController that is causing the problem consists of a back ground image and a Scroll View (SV).
3 images appear in the test SV, yet only 2 appear in production. There appears to be a gap where the first image should appear.
Please note. The first image is the background image for the VC. I set it, then delete it from the array that feeds the scrollview.
Here are the two ViewControllers. Please note I embedded the VC in a TabBar and NavBar controller in test because that is what I have int production.
What is most puzzling is the code is exactly the same. The image URL's are the same. But the number of UIImageViews added to the scrollView are different. Note the last print statement in the code:
func setupList() {
print(foodPairings.count)
let imageStringURL = foodPairings[0].imageURL
let encodedURL = imageStringURL.addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed)
guard let imageURL: URL = URL(string: encodedURL!) else {return}
bgImage.af_setImage(withURL: imageURL)
foodPairings.removeFirst()
print(foodPairings.count)
print(foodPairings.indices)
for i in foodPairings.indices {
let imageView = UIImageView()
let imageStringURL = foodPairings[i].imageURL
let encodedURL = imageStringURL.addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed)
guard let postURL: URL = URL(string: encodedURL!) else {return}
imageView.af_setImage(withURL: postURL, placeholderImage: #imageLiteral(resourceName: "Placeholder"), filter: nil, progress: nil, imageTransition: .noTransition, runImageTransitionIfCached: false, completion: nil)
imageView.tag = i
imageView.contentMode = .scaleAspectFill
imageView.isUserInteractionEnabled = true
imageView.layer.cornerRadius = 20.0
imageView.layer.masksToBounds = true
listView.addSubview(imageView)
//attach tap detector
imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(didTapImageView)))
}
print(listView.subviews.count)
listView.backgroundColor = UIColor.clear
positionListItems()
}
The print statements in Test result in:
4 3
0..<3 4
Production prints the following:
4 3
0..<3 5
Why is listView.subviews.count different in production?
I have resolved this, but it is not clear what the source of the issue was.
In Test, my Scroll View had one subview even prior to me adding the array of UIImageViews. In Production, the Scroll View had two subviews prior to me adding the images in the array.
Just prior to the loop where I add my subviews, I remove all subviews from the ScrollView:
listView.subviews.forEach({ $0.removeFromSuperview() })
for i in foodPairings.indices {
print("SubviewCount: \(listView.subviews.count)")
let imageView = UIImageView()
...
Both my Test and Production macs are running XCode 9 Swift 4. Still remains a mystery why subview count was different.

Applying image to random object

I've created an NSArray with buttons and now I wish to apply an image to a randomly chosen button from that array;
let buttons:NSArray = [button1, button2, button3, button4, button5, button6, button7, button8, button9, button10, button11, button12]
let range: UInt32 = UInt32(buttons.count)
let randomNumber = Int(arc4random_uniform(range))
let buttonstring = buttons.objectAtIndex(randomNumber)
buttonstring.image() = UIImage(named: "code2")
This last piece of code is where I wish to apply the image to the randomly chosen button. But it has an error saying;
Cannot assign to value: function call returns immutable value
If buttonstring is a UIButton, you have to use something like this:
buttonstring.setImage(UIImage(named: "code2"), forState: .Normal)
Hope this helps.

Looping zero-padded numbers in swift - Xcode

Under the SKSpriteNode class, you can do the following to animate an object
private func animate(){
var playerTextures:[SKTexture] = []
for i in 1...3 {
playerTextures.append(SKTexture(imageNamed: "image00\(i)"))
}
let playerAnimation = SKAction.repeatActionForever(
SKAction.animateWithTextures(playerTextures, timePerFrame: 0.1))
self.runAction(playerAnimation)
}
The above code can animate an object using the sequence of images. Here the image files would be image001.png image002.png image003.png
Here come's my question, how can I animate images if the file names are
image001.png
image002.png
...
image009.png
image010.png
image011.png
image012.png
The key point here is the problem with the zero paddings. Any ideas?
Assuming you will only have three digits number you could add your pictures that way:
for i in 1...3 {
let imageNumber = String(format: "%03d", i)
playerTextures.append(SKTexture(imageNamed: "image\(imageNumber)"))
}
This will give you image001, image002 and image003
This requires that you import Foundation at the beginning of your swift file

NSPasteboard with RTF/RTFD Changing Font

I'm working on a utility that pastes images with text. So far the best way I've found to do this was using NSPasteboard and encapsulating the images and text in an RTFD data stream. The problem I'm having is that even though I have no font attributes (I have checked) every time I paste copied code into a document it changes the font to 'Helvetica size 12'. Is it possible to force paste the text and images without changing the font?
void copyData() {
let pboard = NSPasteboard.generalPasteboard()
pboard.clearContents()
let str = NSMutableAttributedString()
for im in images {
let a = NSTextAttachment()
a.image = im
let s = NSAttributedString(attachment: a)
str.appendAttributedString(s)
}
//now I have an rtf with a whole bunch of images
let range = NSMakeRange(0, str.length)
if let d = str.RTFDFromRange(range, documentAttributes: [NSDocumentTypeDocumentAttribute: NSPlainTextDocumentType]) {
pboard.setData(d, forType: NSPasteboardTypeRTFD)
}
pboard.writeObjects(images)
}

Photo changing every day(Xcode, Swift)

I haven't write code for this But I want some help that can it be possible to code so that it shows new photo everyday. for example I have 10 images and I want to display each image for like September 16,17,18, and so on ?
Here you go...
Call method getImageForToday() where ever you want to fetch image for today (This solution will work specific to your case, i.e. as you mentioned you have 10 images)
func getImageForToday() -> UIImage
{
let arrImages = ["image1.png", "image2.png" ... "image10.png"]
var imageName = arrImages[getLastCharacterFromTodayDate()]
return UIImage(named: imageName)
}
func getLastCharacterFromTodayDate() -> Int
{
let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let component = calendar.components(NSCalendarUnit.CalendarUnitDay, fromDate: NSDate())
return component.day % 10
}
You can use the object NSDate to know what day is it and after that doing something.
First you have your dictionnary of image like that :
let images = [ UIImage(named: "image1.png")!, UIImage(named: "image2.png")!, UIImage(named: "image3.png")]
so now, you must know what day is it for the first app openning in exemple.
So you can do that :
let date = NSDate()
You put the element date in UserDefaults. (in order to save it)
You can now display a image. You make a random number and you take UIImage at this random position.
The day after, or the next app opening you recheck the NSDate with the NSDate saved and if it's different you take a other photo.

Resources