Variable in label Name - Swift - swift

Is it possible to use a variable in a label name.
For example, my label is called button1text and I have a variable var x = 1.
Is there a way to do thisbutton(x)text?

No. You can not have variable name in identifier.

Variable names are evaluated at compile time, so no, it's not possible (at runtime).
Alternatively use an array or assign tags to the labels and get the label with viewWithTag

You can use reflection with Mirror. The capabilities are very limited in the context you want but you can try something like:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var button1: UIButton!
#IBOutlet weak var button2: UIButton!
#IBOutlet weak var button3: UIButton!
#IBAction func didTapGoButton(_ sender: Any) {
let mirror = Mirror(reflecting: self)
for child in mirror.children {
if let v = child.label, v == "button2" {
(child.value as! UIButton).titleLabel?.text = "changed"
}
}
}
}

Related

how to use emojis in my project in Xcode and declare them in a dictionary array?

simply I have a uiimage and want to use one of the emojis in that . how can I get some of these emojis and place into my project? this is the place I ll get them from.
https://apps.timwhitlock.info/emoji/tables/iso3166
one more question . next to my uiimage I have a uilabel for currency codes. so to use the image along with the corresponding code do I need to use a dictionary like :
var dict = ["EUR": "imagenameinString"]
or
var dict = ["code" : "EUR", "image": "imagenameinString"
i want to call the currency code and related image/emoji together. This is my code below using a string value for emoji but I get error in this way naturally. how do I edit this code to work? Thank you!
class ViewController: UIViewController {
#IBOutlet weak var amountText: UITextField!
#IBOutlet weak var amountText2: UITextField!
#IBOutlet weak var fromLabel: UILabel!
#IBOutlet weak var fromImage: UIImageView!
#IBOutlet weak var toImage: UIImageView!
#IBOutlet weak var toLabel: UILabel!
let flag = "\u{1F1F8}\u{1F1EA}"
var currencyManager = CurrencyManager()
var from: String = "EUR"
var to: String = "TRY"
var amount: String = "0"
override func viewDidLoad() {
super.viewDidLoad()
amountText.delegate = self
currencyManager.delegate = self
fromImage.image = flag
}

Swift - Can't access struct properties

Learning swift but a little confused as to the below. I have struct created and instantiated, but I cannot access the property of the struct inside of my view controller class unless the struct is inside one my my class methods. See below, why would this be the case?
class WeatherViewController: UIViewController, UITextFieldDelegate, WeatherManagerDelegate {
//create new weather manager struct
var weatherManager = WeatherManager()
//can't access property here, but I can access it inside of functions within this
//class, see below under viewDidLoad()
weatherManager.delegate = self
#IBOutlet weak var conditionImageView: UIImageView!
#IBOutlet weak var temperatureLabel: UILabel!
#IBOutlet weak var cityLabel: UILabel!
#IBOutlet weak var searchTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
//can access property here
weatherManager.delegate = self
}
The problem isn't where the WeatherManager object is declared and created. The problem is that this line:
weatherManager.delegate = self
is a command (technically a statement), not a declaration. (The line above it is a declaration, one that happens to also set the weatherManager property's default value). This is a pretty universal rule in most languages in the C++/Java family -- see short C++ example below. A command (statement) must be inside some method (or function, in non-OOP programming), not at the top level of a file or class. In Swift, actions like setting an object's delegate would typically go in the view controller's viewDidLoad.
int x = 0; // legal: declaring a global variable
x = x + 42; // NOT legal: this is a statement, not a declaraiton
int main()
{
x = x + 42; // legal: now we're inside a function
return 0;
}

macOS Swift TextField.stringValue not returning updated value until I click on something else

I apologize if this has been asked before but I couldn't find what I was looking for online over the last few hours. I'm still functional a noob with swift.
I am trying to store the stringValue of a TextField when I click a NSButton. If I click anywhere and then click on the NSButton the code works perfect but if I don't click the stringValue is still reporting the previous value.
#IBOutlet weak var NameText: NSTextField!
#IBOutlet weak var SaveChangesAccountButton: NSButton!
var selectedAccountItemNumber = NSInteger()
#IBAction func SaveAccountChanges(_ sender: Any)
{
let AccountName = NameText.stringValue
AccountingData.instance.book.account[selectedAccountItemNumber].name = AccountName
}
You have to call validateEditing() on the text field.
And please conform to the naming convention that variable and function names start with a lowercase letter and don't use NSInteger in Swift.
#IBOutlet weak var nameText: NSTextField!
#IBOutlet weak var saveChangesAccountButton: NSButton!
var selectedAccountItemNumber = 0
#IBAction func saveAccountChanges(_ sender: Any)
{
nameText.validateEditing()
let accountName = nameText.stringValue
AccountingData.instance.book.account[selectedAccountItemNumber].name = accountName
}

Why array's append method cannot be used in viewController?

I am beginner of swift. I tried to use array's append method in my code but it doesn't work. How should I implement the array correctly?
The error messages:
Swift Compiler Error Group
ViewController.swift:16:5: Expected declaration
ViewController.swift:11:7: In declaration of 'ViewController'
I tried to use array's append method in my code but it doesn't work.
import UIKit
class ViewController: UIViewController { //Error msg: In declaration of 'ViewController'
#IBOutlet weak var dice: UIImageView!
#IBOutlet weak var dice2: UIImageView!
var dices : [String] = []
dices.append("Hi") //Error: Expected declaration
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func rollPressed(_ sender: UIButton) {
dice.image = UIImage(named: "dice3")
}
}
I expect I can add "hi" into the array dices.
You should call the append inside a function after the vc is fully initated
class ViewController: UIViewController { //Error msg: In declaration of 'ViewController'
#IBOutlet weak var dice: UIImageView!
#IBOutlet weak var dice2: UIImageView!
var dices : [String] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
dices.append("Hi") // e.x here
}
#IBAction func rollPressed(_ sender: UIButton) {
dice.image = UIImage(named: "dice3")
}
}
Or replace
var dices : [String] = []
with
var dices = ["Hi"]
SH_Khan is right. I'll explain why though.
When defining a class, the first level of indentation is only for its methods and properties, aka func, var, and let. (You can also define other classes/structs/enums in there too)
Calling those functions or system functions like Array.append() or print("dog sweat") must happen inside of another function. The reason why is that your application's live logic is literally just functions all the way down. No function gets called unless it's inside of another function first. (The only exceptions are Swift's quick and dirty initializations like setting a default value to a var outside of an init() { } or another function.)
A dog doesn't wake up from its nap unless you make some noise. It won't do it on its own. (crappy metaphor, but yeah)
I hope that made any sense.

Textfield and floats in Swift

I have 2 textfields. If they both has a float value bigger than 100, when you click on my button it should allow you to go to another page.
So far so good, however in my code the text field can't have either int or float or doubles...
What can I do?
As Lukas says you need to convert it to a string. If you are capturing the value in the textfield on button click, you need to convert it, like so:
if let doubleValue = Double(textField.text!) {
}
I think based on what you have said, you need to do something like this:
class ViewController: UIViewController {
#IBOutlet weak var box1: UITextField!
#IBOutlet weak var box2: UITextField!
#IBOutlet weak var Check: UIButton!
#IBOutlet weak var Page1: UILabel!
#IBAction func didPressCheckButton(sender: UIButton) {
if let stringValue = box1.text {
if let doubleValue = Double(stringValue) {
if doubleValue > 100 {
print("Navigate to next page")
}
}
}
}
}
You will need to modify the check so that you check if both text boxes have values over 100, but this is a starting point.