Displaying images with action in swift? - iphone

I'm a kind new to Xcode/swift, I am trying to build a game where 5 pics need to selected randomly, my code looks something like that :
var options = ["1.png","2.png","3.png","4.png","4.png"]
#IBAction func option1(sender: AnyObject) {
var randomNumber = Int(arc4random_uniform(5))
**iphoneChoise.image(options[randomNumber])** /*This line is not correct*/
}
Please help!

Make an #IBOutlet for your image view.
Then, assuming your images are saved in Images.xcassets:
#IBAction func option1(sender:AnyObject){
var randomNumber = Int(arc4random_uniform(5))
yourImageViewIBOutlet.image = UIImage(named: options[randomNumber])
}

You should try something like :
yourImageView.image = UIImage(named: "imageName")
In you case, it should like like this :
var options = ["1.png","2.png","3.png","4.png","4.png"]
#IBAction func option1(sender: AnyObject) {
var randomNumber = Int(arc4random_uniform(5))
iphoneChoise.image = UIImage(named: options[randomNumber])
}
Make sure the images are within the project (inside the Images.xcassets for example).
If it didn't helped, please provide more information : "what" is _iphoneChoise_ and what error are you facing.

You can simplify the code for your random image by using the following code:
var randomImageGeneratorNumber = acr4random_uniform(5) + 1
YourImageView.image = UIImage(named: "\(randomImageGeneratorNumber).png")
This is called "String Interpolation"
Hope this will help you by making your code a bit shorter.

Related

Swift can't get text of label even though the same expression

im programming a calculator app as an exercise project.
I have already used the text of the label before via
calculatorLabel.text
Eventhough I use exactly the same expression in another function, I always get 0 instead of the actual text inside it. I seriously do not understand why that happens. I have already tried using debug mode and stuff but it doesn't work.
here ar the two functions (shortened):
#IBAction func operationButtonTapped(_ sender: UIButton) {
let operation = sender.currentTitle!
lastSender.backgroundColor = UIColor.systemBlue
lastSender = sender
sender.backgroundColor = UIColor.orange
//a switch would be here(deleted)
isTyping = false
let currentNumber = Double(calculatorLabel.text!)!
a = currentNumber
}
#IBAction func changeStateButtonTapped(_ sender: UIButton) {
let operation = sender.currentTitle!
let displayedNumber = Double(calculatorLabel.text!)!
var displayedText = self.calculatorLabel.text!
if operation == "+/-"{
if operation.prefix(1) == "-" {
displayedText.remove(at: displayedText.startIndex)
}
else{
displayedText = "-" + String(displayedNumber)
}
}
else if operation == "%"{
displayedText = String(displayedNumber/100)
}
calculatorLabel.text = displayedText
}
the top one gets the text while the bottom one doesn't...
thank you very much in advance for trying to help me!
I found the answer...
It seems the connection between it and the code was somehow messed up.
To all who have the same problem: right click the component in the storyboard and check the connections!

How to grab other local tag data in Swift?

I am working on saving data process,
because my data is small, so I want to save in local data storage.
I want a make time schedule.
Because I have single 35 buttons and label(each buttons and label are paired), So I am using UIButton tag now. And I have a problem on using other local data "tag".
I tired to make new func on global swift file(same swift file). but it is not able to call tag, because tag is only can use when UIbutton pressed.
I want to use tag property on viewDidLoad(), not only in UIbuttonPressed.
override func viewDidLoad() {
if let items = UserDefaults.standard.array(forKey: "SubjectList") as? [String] {
subjectArray = items
UITextLabel**1**.text = subjectArray**[1-1]**
}
}
#IBAction func buttonPressed(_ sender: UIButton) {
var textField = UITextField()
let newItem = textField.text!
if sender.tag == 1{
self.subjectArray[sender.tag-1] = newItem
print("1")
}
UserDefaults.standard.set(self.subjectArray, forKey: "SubjectList")
}
Create outlet collections for all the paired labels and buttons
#IBOutlet weak var allLbls:[UILabel]!
#IBOutlet weak var allBts:[UIButton]!
In viewDidLoad
if let items = UserDefaults.standard.array(forKey: "SubjectList") as? [String] {
subjectArray = items
subjectArray.indices?.forEach {
allLbls[$0].text = subjectArray[$0]
allBts[$0].tag = $0
}
}

Loading correct image to detail view

I have a TableView app that plays music. The tracks are named: 0.mp3, 1.mp3 etc. They play in a detail view where I also want an image of the cover. I named the cover images: 0.png, 1.png etc.
I tried to load the correct image with the code:
self.bookImage.image = UIImage(named: ("/\(trackID!).png"))
but it doesn't work.
Here's some more of my code:
import UIKit
import AVFoundation
class AudioPlayerVC: UIViewController {
var trackID: Int!
var audioPlayer:AVAudioPlayer!
#IBOutlet var bookImage: UIImageView!
#IBAction func play(_ sender: AnyObject) {
if !audioPlayer.isPlaying{
audioPlayer.play()
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.bookImage.image = UIImage(named: ("/\(trackID!).png"))
trackLbl.text = "Track \(trackID!)"
let path: String! = Bundle.main.resourcePath?.appending("/\(trackID!).mp3")
let mp3URL = NSURL(fileURLWithPath: path)
do
{
audioPlayer = try AVAudioPlayer(contentsOf: mp3URL as URL)
audioPlayer.play()
}
}
}
You need
self.bookImage.image = UIImage(named:"\(trackID).png")
Or
self.bookImage.image = UIImage(named:"\(trackID)")
First, you don't need / character after opening quotation mark.
self.bookImage.image = UIImage(named:"\(trackID).png")
Should work just fine.
1) Please add your images to Assets.xcassets
2) Name images like 0,1,2,3 in Assets.xcassets
3) Write a code:
let trackId = String(trackId)
self.bookImage.image = UIImage(named: trackId)

SD not setting Image pulled from Firebase Storage

I am following Google's guide for getting an image from the storage and then placing it into an imageView using "FirebaseStorageUI", which seems to use SDWebImage.
I have the problem that the image simply is not set. There are no errors in the console. My code:
#IBOutlet weak var imageView: UIImageView!
var ref = FIRDatabase.database().reference()
var storageRef = FIRStorage.storage().reference()
override func viewWillAppear(_ animated: Bool) {
self.getHouseID(){ (houseName) -> () in
if houseName.characters.count > 0 {
self.houseIDLabel.text = houseName // does work correctly
let photoRef = self.storageRef.child("\(houseName)/\("housePhoto.jpg")")
self.housePhotoImageView.sd_setImage(with: photoRef) // not working
} else {
print("error while setting image and house name label")
}
}
}
My Storage looks like this:
The label gets correctly set with the houseName, which is also used in the storage path to retrieve the image. Anything I have missed here?
1. I think the problem is that your awesomehouse/ has a slash in the end.
Try to check which child() your are creating: awesomehouse or awesomehouse/
2. The second possible problem is that you are trying to fetch "housePhoto.jpg" instead of stored housePhoto.
So, it should be:
let photoRef = self.storageRef.child("awesomehouse/").child("housePhoto")
self.housePhotoImageView.sd_setImage(with: photoRef) // should work now
Or it better to save photo to storage with extension ".jpg", then it would be:
let photoRef = self.storageRef.child("awesomehouse/").child("housePhoto.jpg")
self.housePhotoImageView.sd_setImage(with: photoRef) // should work now
Try both. I think it will solve your problem.
Hope it helps
My first guess would be that you are not setting this on the main queue.
Try this:
DispatchQueue.main.async {
self.housePhotoImageView.sd_setImage(with: photoRef)
}
I don't know if it matters that your image file does not have a file extension, that might also be worth trying. Hope this helps

swift - Call a class function in viewController

hi im new to SO so i hope i make everything right.... :)
i started some Days ago iOS programming and no i have a problem that drives me crazy!
Here is the code of the class FactBook:
import Foundation
import UIKit
public class FactBook {
var randomNumberForAll: Int!
let factsArray = [
"Ants stretch when they wake up in the morning.",
"Ostriches can run faster than horses.",
"Olympic gold medals are actually made mostly of silver.",
"You are born with 300 bones; by the time you are an adult you will have 206.",
"It takes about 8 minutes for light from the Sun to reach Earth.",
"Some bamboo plants can grow almost a meter in just one day.",
"The state of Florida is bigger than England.",
"Some penguins can leap 2-3 meters out of the water.",
"On average, it takes 66 days to form a new habit.",
"Mammoths still walked the earth when the Great Pyramid was being built.",
"You can finish the entire FunFacts iOS app course in the time it takes to set up the emulator for the Android course"
]
let imagesArray = [
UIImage(named: "ants.jpg"),
UIImage(named: "ostriches.jpg"),
UIImage(named: "olymp.jpg"),
UIImage(named: "bones.jpg"),
UIImage(named: "light.jpg"),
UIImage(named: "bamboo.jpg"),
UIImage(named: "florida.jpg"),
UIImage(named: "penguins.jpg"),
UIImage(named: "habit.jpg"),
UIImage(named: "mammoth.jpg")
]
func randomFact() ->String {
//Count
var arrayCount = UInt32(factsArray.count)
//Random Number from count
var unsignedRandomNumber = arc4random_uniform(arrayCount)
//Random Number as Int
var randomNumber = Int(unsignedRandomNumber)
self.randomNumberForAll = randomNumber
return factsArray[randomNumber]
}
func randomImage() -> UIImage {
var imageRandom = randomNumberForAll
return imagesArray[imageRandom]!
}
}
Here is the ViewController:
import UIKit
class ViewController: UIViewController {
//Lable, Structs etc.----------------------------------NEU----------------------------
#IBOutlet weak var funFactLable: UILabel!
#IBOutlet weak var funFactButton: UIButton!
#IBOutlet weak var imageView: UIImageView!
let colorWheel = ColorWheel()
var counter = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//Loads first Label Text
funFactLable.text = "An interestig Fun Fact comes with one push!"
funFactButton.setTitle("For the first Fun Fact - Push!", forState: UIControlState.Normal)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//ACTIONS-------------------------------------------------------------------------------------
#IBAction func showFunFact() {
var randomColor = colorWheel.randomColor()
var randomImage = FactBook.randomImage()
var randomFact = FactBook.randomFact()
counter++
//BackgroundColor change
view.backgroundColor = randomColor
//Button-TextColor change
funFactButton.tintColor = randomColor
//Button-Title = Counter + Text
funFactButton.setTitle("\(counter). Fun Fact", forState: UIControlState.Normal)
//fadeIn fadeOut FactLable
self.funFactLable.fadeOut(completion: {
(finished: Bool) -> Void in
self.funFactLable.text = randomFact
self.funFactLable.fadeIn()
})
//fadeIn fadeOut ImageView
self.imageView.fadeOut(completion: {
(finished: Bool) -> Void in
self.imageView.image = randomImage
self.imageView.fadeIn()
})
}
}
so the problem is, i cant call the functions (randomFact and randomImage) in the ViewController.
But always the Error Missing argument for parameter #1 in call comes up.
When i change the class factbook to struct i can call the funcĀ“s but then the self.randomNumberForAll doesnt work.
What i just want is to use the randomnumber from the func randomFact() in the func randomImage()....
Thank you if u can help me :) !!!!
I hope this isn't a case of the blind trying to lead the blind as I'm new to swift, but I took this course too recently and was playing around with the code similarly to you. Seems like loading in the Factbook like you did Colorwheel should eliminate your missing parameter error. Unlike the colorwheel though, maybe it has to be a variable instead of a constant, so that you can store and change your randomFactForAll:
let colorWheel = ColorWheel()
var factBook = FactBook()
little late, hope this helps
Need to add keyword "class" to your functions randomFact() and randomImage() to make them as class functions.
Please check the following question for similar issue.