Creating a word game - ios

I'm creating a word game using UIKit, and I want to represent the entire alphabet for the user in order to solve the puzzle, here is my code:
var emptyPos = [0]
#IBOutlet var pos1: UILabel!
#IBOutlet var pos2: UILabel!
#IBOutlet var pos3: UILabel!
#IBOutlet var pos4: UILabel!
#IBAction func btnA(sender: UIButton) {
letters(sender)
}
#IBAction func btnB(sender: UIButton) {
letters(sender)
}
#IBAction func btnC(sender: UIButton) {
letters(sender)
}
#IBAction func btnD(sender: UIButton) {
letters(sender)
}
func moveLetter (pos: UILabel, btn: UIButton) {
UIView.animateWithDuration(0.5, animations: { () -> Void in
btn.center = pos.center
})
}
func letters (btn: UIButton) {
switch emptyPos.count {
case 1:
moveLetter(pos1, btn: btn)
emptyPos.append(0)
println(emptyPos)
case 2:
moveLetter(pos2, btn: btn)
emptyPos.append(0)
println(emptyPos)
case 3:
moveLetter(pos3, btn: btn)
emptyPos.append(0)
println(emptyPos)
case 4:
moveLetter(pos4, btn: btn)
emptyPos.append(0)
println(emptyPos)
default:
println("Error")
}
}
The idea is the user has to click on a letter after letter to move them towards the empty labels and figure out the right word, and as you can see I went with making each letter a button and each empty space a label, but was wondering if there is a better way than creating 26 buttons for each letter. Linking all the buttons to a single function will not work because then I will have to rely on sender.tag which I cannot pass to my function in order to move the letter. So should I continue with what I'm doing or is there some better way to do this ?

if you make a custom UIButton you can add extra properties to the button, then change the sender of the #IBAction to your custom class, then just pass the button to your moveLetter and it can know what to do based on the information supplied by the button. then they can all share the same button press function
then if your buttons subclass has a #property string called ButtonLetter, you can define what its value is right in the storyboard instead of manually doing it in code for all of the buttons by giving it a runtime attribute like in the screen shot below
or you could be lazy and just get the text of the button and read what letter it is, but i would say this is a more proper way of going about it, cause this can apply to any type of button where maybe the text on the button isnt actually the value you want to use to do some computation when the button is pressed, but in your case it just so happens to be that way.

Related

Swift UIbutton is clicked add a string and when clicked again it removes it

I'm a beginner in swift, I'm making an app in storyboard UIKit, and I need some help basically I need to set up a view controller that has buttons on it that when clicked add a string on the bottom of the VC, and if clicked again it will remove that same string. On the VC there going to be multiple buttons like this for options also on the bottom of the VC I need the label to update during the app also it should display like this for example. "Football","Basketball","Golf". It needs to be displayed just like that on the bottom with quotes and commas. I've to turn to make action buttons with a global array and put that inside each button but I can't figure out how to remove it when the button clicked again, also if you click the button again it'll add the same thing again so in the array you'll have two of the same strings. Anything would help.
P.S I need to do this in UIkit and Storyboard
You can make list of outlets to an array UIButton, handle list of actions when click into UIButton with a function. Using 'isSelected' property of UIButton to distinguish 'delete' or not.
class ViewController: UIViewController {
#IBOutlet weak var descriptionLabel: UILabel!
#IBOutlet var allButtons: [UIButton]!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func didTapButton(_ sender: UIButton) {
sender.isSelected.toggle()
_updateDescription()
}
private
func _updateDescription() {
descriptionLabel.text = allButtons
.filter { $0.isSelected }
.compactMap { $0.titleLabel?.text }
.map { "\"\($0)\"" }
.joined(separator: ", ")
}
}

Linking two (or more) UISegmented Controls

I'm trying to get the answer from my first segmented control to then automatically select the answer to the second (and more) segmented controls, if the selected answer is No.
So Question1 segmented control (Yes, No, N/A), if No is selected, then make answer to Question2 (and Q3,Q4 etc) segmented control to N/A.
I can get it to work on Question1 alone, ie press No but changes to N/A on Question1, but I want it to leave Question1 as No, but then change Question2 etc to N/A.
I tried changing sender to Question2, but that doesn't work.
#IBOutlet weak var Queston2: UISegmentedControl! //Will need to add same for Q3 etc
#IBAction func Question1(_ sender: UISegmentedControl) {
if sender.selectedSegmentIndex == 0 {
//Do stuff
}
else if sender.selectedSegmentIndex == 1 {
sender.selectedSegmentIndex = 2 // Change button to 'N/A', works for this question, but i want it to change Question2, not Question1.
#IBAction func Question2(_ sender: UISegmentedControl) { // generally repeats as Question1 above.
I've found a few similar answers, but they seem far more complicated than I think I need.
This is basically what you could do:
class ArrayOfSegsViewController: UIViewController {
#IBOutlet var q1SegControl: UISegmentedControl!
#IBOutlet var q2SegControl: UISegmentedControl!
#IBOutlet var q3SegControl: UISegmentedControl!
#IBOutlet var q4SegControl: UISegmentedControl!
#IBOutlet var q5SegControl: UISegmentedControl!
#IBAction func q1SegControlChangeed(_ sender: UISegmentedControl) {
if sender.selectedSegmentIndex == 0 {
// do stuff
} else if sender.selectedSegmentIndex == 1 {
// set all others to "N/A"
[q2SegControl, q3SegControl, q4SegControl, q5SegControl].forEach {
$0.selectedSegmentIndex = 2
}
} else {
// do stuff
}
}
}
In the == 1 block, you create an array of the other segmented controls and loop through, saying "for each control, set the selected segment index to 2."
Side notes: use
lowerCaseFirstChar
for variables and function names. Use
UpperCaseFirstChar
for classes / structs / enums / etc.

Changing label text to what user inputs into UITextField

This is a very basic question but I'm not sure what the problem is. I'm trying to make a simple "hello world" program where the user inputs what they want into the textfield and whatever they enter goes into the label. However, nothing seems to be happening and I'm unsure why since my push function worked exactly how I expected it to.
import UIKit
class ViewController: UIViewController {
#IBOutlet var PopUp: UITextField!
#IBOutlet weak var HelloWorld: UILabel!
#IBAction func Push(_ sender: UIButton) {
PopUp.isHidden = false
PopUp.text = "hello World"
}
#IBAction func send(_ sender: UITextField) {
HelloWorld.text = sender.text
}
}
Based on the code you provided, func send is an unknown to me, as to whether or not it is even firing. func send might be called, might not, either way, it is strange to see a _ sender: UITextField for an IBAction.
What event are you firing related to the UITextField? Are you trying to update your HelloWorld UILabel as the user types in the UITextfield?
To update your UILabel with whatever has been typed in your UITextField, you just need a UIButton Touch Up Inside IBAction. I think you can delete IBAction func send completely, unless you are trying to update the UILabel as the user types in the UITextField. Make sure you remove the IBAction Outlet from your Storyboard if I am correct about this point.
Based on the code you provided the Push func does not set text in your UILabel. I am assuming Push is an UIButton Touch Up Inside IBAction. You can set your HelloWorld UILabel text, in func Push, you do not need to use the sender of the event, try this and you will see the HelloWorld UILabel text populated:
#IBAction func Push(_ sender: UIButton) {
//PopUp.isHidden = false //why are you doing this? the UITextField PopUp should already be visible if you are typing text into it, so this code is superfluous as the value of PopUp.isHidden is already false
HelloWorld.text = PopUp.text
PopUp.text = "hello World"
}
If you are trying to have your UILabel display the text as you type into the UITextField you should clarify your question. And if it is the case you will need to make your UIViewController a UITextFieldDelegate
Here is the one way of approach :
override func viewDidLoad() {
super.viewDidLoad()
PopUp.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged) // when textfield is edited this will call
}
func textFieldDidChange(_ textField: UITextField) {
HelloWorld.text = textField.text
}

How to use one IBAction for multiple buttons in Swift?

I have multiple buttons each one with the ability to switch the language of the app. Instead of having to create multiple IBActions for each button is there a way to have them all connected to one IBAction and change the language based on the button pressed? I'm thinking a switch statement would be good to use in this situation but not exactly sure how to set it up.
In Interface Builder, select the Attributes Inspector and set the Tag for each button with a unique number, then you can do something like this:
#IBAction changeLanguage(sender: AnyObject) {
guard let button = sender as? UIButton else {
return
}
switch button.tag {
case 1:
// Change to English
case 2:
// Change to Spanish
case 3:
// Change to French, etc
default:
print("Unknown language")
return
}
}
To connect the action to multiple buttons: in Interface Builder, right-click ViewController in the view hierarchy, then left-click to drag the action connection to each button.
Yes, a switch statement is the way to go here. For a UIButton, you link it to a selector that is called when the user interacts with the button, generally the TouchUpInside event. The addTarget method, and valid selector signatures (apple.com) Of these, you want to use a method in the format #IBAction func doSomething(sender: UIButton) or #IBAction func doSomething(sender: UIButton, forEvent event: UIEvent), so that a reference to the button that triggered the event is passed to the selector.
In your ViewController code, you'll have references to your UIButtons (possibly in a storyboard, or created manually.) Let's say you have
#IBOutlet weak var frenchButton: UIButton!
#IBOutlet weak var spanishButton: UIButton!
#IBOutlet weak var englishButton: UIButton!
You would connect all of them to the same method, and branch the logic based on which one was the sender. e.g.:
#IBAction func changeLanguage(sender: UIButton) {
switch sender {
case frenchButton:
// Change Language to French
print ("C'est si bon")
case spanishButton:
// or Spanish
print ("Muy Bueno")
case englishButton:
// or English
print ("It's pretty cool")
default:
break
}
}
Note: Case statements in Swift must be exhaustive, so you have to include a default case, even though it should never be called.
Do not set tag if you have reference to the button.
You can just compare the reference instead of tags. This way, you won't introduce a new bug, because unlike a tag that you type yourself, reference is created by compiler automatically.
#IBOutlet weak var firstButton: UIButton!
#IBOutlet weak var secondButton: UIButton!
#IBOutlet weak var thirdButton: UIButton!
#IBAction changeLanguage(sender: UIButton) {
if sender == firstButton {
} else if sender == secondButton {
} else if sender == thirdButton {
}
}

How to hide button after click

I create Start_button and make #IBOutlet and #IBAction
#IBOutlet weak var Start_button: UIButton!
#IBAction func Start_button(sender: AnyObject)
Now, i want hide button after click. I try this, but this don't work:
#IBAction func Start_button(sender: AnyObject)
{
Start_button.hidden = true;
}
Error message:
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)
How i can hide this button?
Thanks for helping!
Its nil because you probably haven't connected it from your storyboard/nib. You need to connect the outlet, you can't just create an outlet in code and expect it to be connected to the visible element. The same goes for your action. #IBOutlet / #IBAction stands for Interface Builder Outlet/Action, which means you have to connect them in Interface Builder.
Also its better if your action uses the sender, and not a local variable (when its pointing to the same thing). And you shouldnt use ;at the end of the line.
#IBAction func Start_button(sender: UIButton) // Change to UIButton
{
sender.hidden = true
// OR
// (sender as! UIButton).hidden = true
}
#IBAction func button_nameA(sender: AnyObject) {
// show hidden buttons
self.Target_Object.hidden = false
}
So when you click the A buttons its automaticly send to you target and in target also you have to hide button if you working single view app

Resources