Calling an ImageView variable inside an if statement - ios

I'm using Swift in Xcode and that's my issue:
I want to declare a variable where I want to store an UIImageView (Not an UIImage, but an UIImageView), so I tried something like that
var nameVariable = UIImageView()
Then I need to recall this nameVariable inside an if statement
if(\(nameVariable).center.y > something){..}
I tried using "(nameVariable)" but it doesn't work, can you help me?

Declare Variable
var img=UIImageView()
Then use it
if img.center.y > 50 {
//do stuff here
}

Related

How can I make an UIImageView change depending on the chosen number?

I'm creating an app which chooses two random cards out of a 52-card deck. Then, if one of the card is strong (in my case, strong cards are "10" or stronger) I want it to show an image "yes" (tick). If both of the cards are weak, then I want it to show an image "no" (cross). I've been trying to find a problem, but every time I change something, a new type of error occurs.
I tried to set an unknown output type in func resultOfShuffle, I tried creating and naming an outlet for my UIImageView couple of times.
let cardArray = ["1.png", (...), "52.png"]
// All of the cards, from 2 to Ace (with every color). Number "33" is a card 10.
...
let cardResults = ["yes.png"]
...
#IBOutlet weak var theResult: UIImageView!
...
func randomizeCards() {
chooseCardOne = Int.random(in: 0 ... 51)
chooseCardTwo = Int.random(in: 0 ... 51)
...
func resultOfShuffle(firstCard : Int, secondCard : Int) -> UIImageView {
if firstCard > 33 {
return theResult.image = UIImage(named: cardResults)
}
}
And now, the return of the last func resultOfShuffle is wrong - telling me: Use of unresolved identifier 'theResult'. I also tried to find the solution to this problem, but it is kinda tricky and I don't get it.
That's how my app looks like:
https://imgur.com/a/kjdcqcO
Is every statement executed in the same ViewController?
It should recognize theResult as a UIImageView, then.
Update
The problem is, as solved in the comments, based on the scope of the function declaration. Since it is declared outside of the class where theResult is defined, it can't get access to it.
The solutions could be passing the variable as an argument to the function, or declaring the function in the same scope of the variable - inside the ViewController.
Other notes
You are, anyway, trying to return something with this line:
theResult.image = UIImage(named: cardResults)
which doesn't evaluate to a type, but simply sets the image of the view to what's in cardResults. Therefore, you shouldn't return anything, but merely using this function in order to update the content of the view - this means you should use a Void return type.
Furthermore, you are passing to the image initializer a [String] type, while you should just pass a String.
Try something like this:
func resultOfShuffle(firstCard : Int, secondCard : Int) {
if firstCard > 33 {
theResult.image = UIImage(named: cardResults[0])
}
}

Swift 4 : Adding UIView into the array programmatically with for loop

I'm using scrollView paging and I want to add UIViews into the scrollView programmatically with for loop. But I guess I'm missing something.
Here is my code :
func createSlide() ->[Slide]{
for i in 0..<datas.count{
slideAll?.append(Bundle.main.loadNibNamed("ViewTest", owner: self, options: nil)?.first as! Slide)
slideAll![i].testLabel.text = datas[i]
}
return slideAll!
}
Is this possible that I can add UIView like that? If I can, how can I fix this code piece?
Edit :
I realized that I initialize the slideAll with no value on the top like that :
var slideAll:[Slide]?
How can I initialize this correctly? Should I initialize this on the function?
for i in 0...datas.count will loop to the last slot array+1, then it will yell error because at that index there's no value, you should use for i in 0..<datas.count or for slide in datas instead
Instead of this line:
var slideAll:[Slide]?
say this:
var slideAll = [Slide]()
Then remove the Optional unwrap notations from your references to slideAll in the rest of the code.
Make sure datas is initialized.
use for-loop as below:
for text in datas {
// DO SOMETHING
}
And I hope, you are subview-ing the views on uiscrollview somewhere in the code and it is not mentioned in the above question?

property initializers run before 'self' is available error Swift [duplicate]

This question already has answers here:
Property initializers run before 'self' is available
(2 answers)
Closed 5 years ago.
I have a SearchURL String which gets a chose variable from previous view controller. And with this gotten variable, SearchURL should be used in callAlamo func. But I have an error:
Should I use async dispatch or something like this? I've tried many things like putting everything in viewDidLoad() but did not work. Anybody could help?
You can use a computed property like so:
var searchURL: String {
return "https://theurlIcantcopybecauseitsascreenshot.com/\(chosed!)"
}
Note that this will be recomputed every time you access it, so if chosed changes, so will searchURL. You can also make it an implicitly unwrapped optional like in Paulo Mattos' answer, or you could make an initializer that takes chosed as a parameter (see comments below, for a caveat). Then you could set searchURL in init.
Also, just a nitpick to let you know, Swift standard is to have variables in camel case (searchURL instead of SearchURL).
The viewDidLoad will not be called everytime you enter your view controller, as such, you may not detect updates to the chosed property (among other tricky issues).
You could do it in viewWillAppear method instead:
var SearchURL: String!
overide func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
SearchURL = "...\(chosed!)..."
...
}
Or you could use a lazy variable:
lazy var SearchURL = {
return "...\(self.chosed!)..."
}()
Or use a computed property as suggested by Connor Neville below.

How to declare a constant that can be accessed by multiple viewcontrollers in Swift?

I have an app I'm working on that has various viewcontrollers that use the same constants.
ex.
let wrongAnswerBanner = UIImageView(image: UIImage(named: "torn_banner"))
I tried declaring the constant outside the viewcontrollers but whenever I try to call the constant by using self.
self.wrongAnswerBanner.hidden = false
I get the error: Value of type 'ViewController1' has no member 'wrongAnswerBanner'. How can I declare these constants without having to redeclare them within each individual viewcontroller?
You can declare the constant outside of a class scope and access it directly from any file inside the module.
File 1
let MyConstant = "MyConstant"
class A {
}
File 2
class B {
// use MyConstant directly (eg. print(MyConstant))
}
I usually do this for UITableViewCell identifiers. I declare them on top of my UITableViewCell subclass and use them on the ViewController file. It's worth nothing though (as other developers mentioned) that UIImageView might not be a good candidate for constants. You can also make use of Enums if that makes sense for your problem.
Just try to call the constant without self
Create a struct with constants:
struct Constant {
static let SomeConstant = "hey"
}
then you can get the value from any class by
let constant = Constant.SomeConstant
According to me you have to create one AppConstant.swift file in your application ,then just add this line in AppConstant.swift file
let wrongAnswerBanner = UIImageView(image: UIImage(named: "torn_banner"))
Then in any of controller you can easily access wrongAnswerBanner without using self

Pass a Class (UILabel) with its properties through a function Swift

I am wondering if anyone knows how to (if possible) pass a UILabel through a function while being able to access and change its properties? Here's what I have:
func plusMinusChange(minus: UILabel, plus: UILabel) {
if (minus.hidden) {
minus.hidden=false
plus.hidden=true
} else {
minus.hidden=true
plus.hidden=false
}
}
And here's how I am calling it:
plusMinusChange(firstMinus, firstPlus)
I know this is probably really illogical but I want to give it a try anyways. If you were wondering, firstMinus and firstPlus are linked to UILabels on the storyboard.
Calls to methods (that is, funcs defined within a class or other type) require parameter labels for the second (and subsequent) parameter but not the first. If you want to change which labels are required at the call site, you change the declaration.
To require a label on the first parameter:
func plusMinusChange(#minus: UILabel, plus: UILabel) {
To require no label on the second:
func plusMinusChange(minus: UILabel, _ plus: UILabel) {
There is no need to use a conditional if there. You can use ! in front of the property to toggle its value as follow:
minus.hidden = !minus.hidden
plus.hidden = !plus.hidden

Resources