How to use random variable to choose correct button in swift - swift

The title might not be the best explanation of what I want but I couldn't think of a better way to describe it.
#IBOutlet var button0: UIButton!
#IBOutlet var button1: UIButton!
#IBOutlet var button2: UIButton!
var num = (arc4random()%3);
basically I want to use the variable 'num' to choose which button and make it hidden based off the random number. Is there a way to use the variable in a a simple line like "button(num).hidden = true" or something like that?

[button0, button1, button2][num]

Basically, all you want to do is create an array of UIButtons!, and then set array[num].enable = false.

you can basically store your buttons into a array of UIButton, and then use this array randomly.
Code
self.buttons.append(button0)
self.buttons.append(button1)
self.buttons.append(button2)
self.buttons[Int(num)].hidden = true

var num = Int(arc4random_uniform(3))
let buttons:[UIButton] = [button0,button1,button2]
buttons[num].hidden = !buttons[num].hidden

Create an array that stores all your UIButtons
var buttonsArray: [UIButton]!
Access one of the UIButtons from the Array randomly and hide the accessed UIButton
var randomNum: Int = Int(arc4random()%3)
var button = buttonsArray[randomNum]
button.hidden = true

Related

Setting the text of a UILabel with a constant

I am a total newby to xCode and Swift so please excuse me if this question is silly.
I am trying to update 2 UILabels and a UIImageView by using the sender.currentTitle of the button pressed.
If a user presses the 'Honduras' button then I want to populate the 2 UILabel with it's corresponding information and the UIImageView with its corresponding image file.
I have the first UILabel working and the UIImageView working but cannot find a way to populate the 2nd UILabel with its corresponding text (which is stored in a constant).
UILabel 1 is called #IBOutlet weak var countryLabel: UILabel!
UILabel 2 is called #IBOutlet weak var peopleLabel: UILabel!
UImageView is called #IBOutlet weak var peopleUIImageView: UIImageView!
The information/file name I want to pass into these 3 are called:
"Honduras"
let peopleHondurasText = "The Lenca"
"peopleHonduras.png"
I have the UILabel 1 working like this:
countryLabel.text = sender.currentTitle
I have the image working by calling this func:
func findCountryImages() {
peopleUIImageView.image = UIImage(named: "people\(countryLabel.text! .filter { !" ".contains($0) }).png")
}
and I am trying to call the constant "peopleHondurasText" like I did the UIImage but it isn't working.
Here is my very amateur code:
peopleLabel.text = "people\(countryLabel.text! .filter { !" ".contains($0) })Text"
Where this:
"people\(countryLabel.text! .filter { !" ".contains($0) })Text"
Should be equal to the constant named:
peopleHondurasText
I want to be able to do this so if a user clicks on any country button it will populate those 2 UILabels and UIImageViews with that countries text and images.
I know I must be doing something fundamentally incorrect or maybe going about this complete in the wrong but if anyone could let me know either how to pass the constant name into the UILable
or tell me that you cannot do this and I should try something different, that would be greatly appreciated.
How come you don't just do:
peopleLabel.text = peopleHondurasText

How to generate Labelname from a variable? (how to cast a string to UILabel)

I want to refer to a label based on the title of the button pressed.
I have a plenty of buttons, that I connected together in a single action. I want to be able to refer to only one label, that corresponds to the name of button pressed.
The Label names are: aLabel, bLabel, cLabel ...
The buttons pressed are titled "a", "b", "c"...
I ame creating the string with name of the label i want to refer to, but I can't use it as label name to change this particular label values.
I want to use this string to refer to the corresponding label, to change it title, color, and so on.
I tried, casting, looking for a function that changes strings into UILabels. I was also thinking about an array with pointers to the Labels, but I didn't succed even with establishing a pointer to a single Label...
//My code
#IBOutlet weak var a: UIButton!
#IBOutlet weak var b: UIButton!
#IBOutlet weak var c: UIButton!
#IBOutlet weak var aLabel: UILabel!
#IBOutlet weak var bLabel: UILabel!
#IBOutlet weak var cLabel: UILabel!
var currentLabel : String
#IBAction func FieldDisplay(_ sender: UIButton) {
currentLabel = sender.currentTitle! + "Label"
currentLabel.text = "OK"
}
//what I tried
(UILabel)currentLabel.text = "OK"
currentLabel = currentLabel.to.UIlabel
When interface objects are associated in multiple pairs like this — a series of button–label pairs, as you have it — there are two approaches commonly used. One is to assign each pair a tag. For example, in the storyboard, the first button would have tag 1, and the first label would have tag 101. Then the second button would have tag 2, and the second label would have tag 102. And so on.
So now in your IBAction function you look at the tag of the sender, add 100 to it, and call viewWithTag on your view to find the corresponding label.
The other possibility is to use outlet collections. Instead of three button outlets you have one array-of-button outlet; so too for the labels. Now in your IBAction function you get the firstIndex of the button in its array; that, if you've set this up correctly, is the index of the corresponding label in its array.
Remove all outlets and create 2 collections
#IBOutlet var allBts: [UIButton]!
#IBOutlet var allLbls: [UILabel]!
then hook all labels / btns to each , and set a tag for each group ( lbl1 && btn1 tag = 0 , lbl2 && btn2 tag = 1 and so on)
#IBAction func FieldDisplay(_ sender: UIButton) {
allLbls[sender.tag].text = sender.currentTitle! + "Label"
}
You can use value(forKey:) method
#IBAction func buttonTapped(_ sender: UIButton) {
if let currentLabel = value(forKey: sender.currentTitle! + "Label") as? UILabel {
currentLabel.text = "OK"
}
}
https://developer.apple.com/documentation/objectivec/nsobject/1412591-value

I can't delete left border of Image in UITableViewCell

I want to create a tableview with foods. Every cell must have:
1. Image
2. Title
3. Description
I want to move the image on the left of the cell but I can't. As you can see there is a "border on the left of the cell".
I have write this code to remove the 15px left border that apple has as default:
tableView.separatorInset = .zero
tableView.layoutMargins = .zero
The image has left constraints 0 but nothing happens.
Also if I remove the image from storyBoard, nothing happens. It's still there. (If I delete cell.imageView?.image = item.image from my code the image will removed)
Also As you can see I have constraints between image and labels but the text is behind the image.
What can I do? Thanks!
I think it's because you're using the UITableViewCell default ImageView, you should name your imageView with a different name from 'imageView'
iDevid I followed the steps from link https://www.ralfebert.de/ios-examples/uikit/uitableviewcontroller/custom-cells/ that you send me. I solved my problem with the left border but now I have problem with the constraints.
I want a screen like this:
But the result is like this:
Here is my class for the custom cell:
class HeadlineTableViewCell: UITableViewCell {
#IBOutlet weak var headLineImageView: UIImageView!
#IBOutlet weak var headLineTitleLabel: UILabel!
#IBOutlet weak var headLineDescriptionLabel: UILabel!
#IBOutlet weak var headLineIngredientsLabel: UILabel!
#IBOutlet weak var headLinePriceLabel: UILabel!
}
I have give them text:
cell.headLineTitleLabel?.text = item.name
cell.headLineDescriptionLabel?.text = item.description
cell.headLineIngredientsLabel?.text = item.ingredients
cell.headLinePriceLabel?.text = ("\(item.price)0€")
And the constraints are:
For the imageView:
For the Label 1:
For the Label 2:
For the Label 3:
For the Label 4:
Can anybody help me?

How can I create a function for multiple labels in a stack?

I have 3 labels and I want to generate random numbers for each of them. I use GKRandomSource class in function, thats ok. The problem is, if I want to have much more labels (ie. 30) and all with same action, I need to reference all labels one by one to IBAction, I need to state all labels one by one in func code… I’ve been searching for a shorter way, maybe put them all in 3 stacks (10 labels for each stacks) and trigger, but I got nothing. I tried outlet collections (as we use in UIButtons) but it doesn’t let me to change label text.
How can I use a function for multiple labels with no-repeat?
Example;
let allNumbers = [Int](1...99)
var shuffledNum = [Int]()
#IBOutlet weak var labelOne: UILabel!
#IBOutlet weak var labelTwo: UILabel!
#IBOutlet weak var labelThree: UILabel!
func generateNumbers() {
shuffledNum = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: allNumbers) as! [Int]
let threeNumbers = shuffledNum.prefix(3).sorted()
labelOne.text = String(threeNumbers[0])
labelTwo.text = String(threeNumbers[1])
labelThree.text = String(threeNumbers[2])
}
you can make the array of UILabel's and put all the outlets in the same array then you can use for loop to do operations on each of them.
for example:
#IBOutlet var formLabels: [UILabel]!
and can do as:
formLabels.forEach { label in
label.text = ""//put your random number function here
}
see its working after adding both outlets I have also shown the connection in the storyboard the connection exists

Swift: Generate Identifier for Variable

I have a large list of NSButtons (80+) that I assign to an array. I've used a numbering scheme to name them and I'd like to generate the identifiers for them instead of calling them directly by name one at a time.
#IBOutlet weak var button120: NSButton!
#IBOutlet weak var button121: NSButton!
var buttons [NSButton]()
Currently (in ViewDidLoad()) I'm doing the equivalent of:
buttons = [ button120, button121 ]
I'd prefer to do something like:
for index in 120...121 {
buttons.append("button\(index)".toIdentifier)
}
Can this be done in Swift?
This might be an easier solution, view is the parent view of the buttons
let buttons = view.subviews.filter { $0 is NSButton}