How to use one IBAction for multiple buttons in Swift? - ios

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 {
}
}

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: ", ")
}
}

How to get context of what Object corresponds to a certain UISegmentedControl

Below you can find an image of a UITableViewCell subclass that I've created. Each cell corresponds to a game that is played between two contestants, and has a winner, defined by the selected control (that in the editor says "first" and "second"). If this winner value is changed, I want to update that game's information and store it in Core Data. The problem is that when I create an IBAction connection to my storyboard, and it gets triggered when the winner is changed, it has no context or knowledge of what game it belongs to, and therefore I can't figure out which game to update the winner of.
How do I get context of the game that was acted on in this IBAction winnerChanged() method? Could I somehow use the superView or superClass of the UISegmentedControl to get more information about the UITableViewCell as a whole?
#IBAction func winnerChanged(_ sender: UISegmentedControl) {
os_log("Saving games because winner was changed", type: .debug)
// need to know what game to change the winner of here
self.allGames.forEach({ updateOrCreateGame(game: $0) })
}
Here's my code for my UITableViewCell subclass:
class ConferenceResultsTableViewCell: UITableViewCell {
#IBOutlet weak var gameWinnerControl: UISegmentedControl!
#IBOutlet weak var confidenceTextField: UITextField!
#IBOutlet weak var confidenceAverageAllUsersLabel: UILabel!
}
Typically you create such #IBActions right inside the cell. From your question, I assume that the method #IBAction func winnerChanged(_ sender: UISegmentedControl) defined somewhere in your controller.
It would be much easier and also resolve your question if you create a dedicated class for your cell with an implementation of that method.
This will allow you to hook your cell with a concrete CoreData's object (through identifier in an example below). All you need to do is to call setup method somewhere from cellForRow of your controller/data source.
final class MatchCell: UITableViewCell {
#IBAction func winnerChanged(_ sender: UISegmentedControl) {
...
}
func setup(with match: Match) {
self.matchId = mathc.id
...
}
}
if you still need that updateOrCreateGame method inside your controller you can pass a callback onUpdateRequested: (Match) -> Void in setup method and call that callback from winnerChanged method.

How do I make two UIButtons perform like radio buttons in Swift?

I have two UIButtons that I want to use to set an A/B value to a variable before I save data to a database. I want a button to become selected when tapped, and deselected when the other button is tapped, and vice versa. What is a good solution for accomplishing this programmatically or in Interface Builder?
In order to set an "A/B value" as you mention, the easiest option would be to use a UISwitch or -in the general case of possibly more than 2 options- a UISegmentedControl (as #rmaddy suggested in the question's comments) .
These controls have built-in the "choose just one out of many" functionality that you are looking for.
The drawbacks of the switch are:
It has to be either on or off (does not support a selection state of "neither A nor B")
You can't have separate title labels for each state.
If you still want two separate UIButton instances, you can:
Have references to both buttons in your view controller (#IBOutlets wired using Interface Builder), e.g.:
#IBOutlet weak var leftButton: UIButton!
#IBOutlet weak var rightButton: UIButton!
Implement the action method for both buttons in such a way that it sets the selected state of the tapped button, and resets the other one. For example:
#IBAction func buttonAction(sender: UIButton) {
if sender == leftButton {
leftButton.isSelected = true
rightButton.isSelected = false
} else if sender == rightButton{
leftButton.isSelected = false
rightButton.isSelected = true
}
}
This is a quick-and-dirty solution for just two buttons. If you want a generic radio group of n-buttons, there are open source solutions on GitHub, etc...
Try this.
First create both button separate #IBOutlet.
#IBOutlet weak var btnYes: UIButton!
#IBOutlet weak var btnNo: UIButton!
Set Both Button Tag Like this and you also set tag using storyboard.
override func viewDidLoad() {
super.viewDidLoad()
btnYes.tag = 1
btnNo.tag = 2
}
Implement Common #IBAction method for both buttons
#IBAction func btnYesNoTapped(_ sender: UIButton) {
if sender.tag == 1 {
self.IsBtnSelected(isSelect: true, with: self.btnYes)
}else {
self.IsBtnSelected(isSelect: true, with: self.btnNo)
}
}
Create Custome Method
func IsBtnSelected(isSelect:Bool,with sender:UIButton){
self.btnYes.isSelected = false
self.btnNo.isSelected = false
sender.isSelected = isSelect
}
you can use following function for creating a radio button behaviour, you have to btn outlet to be selected and array of both outlets to this function. instead ofcolor you can also compare images and set images. for getting a required value yo can create a variable in viewcontroller and assign this variable a value in IBAction of btn and you can call this function from IBAction.
func radioButton(_ btnToBeSelected: UIButton, _ btnArray: [UIButton]) {
for btn in btnArray {
if btn == btnToBeSelected {
btn.backgroundColor = UIColor.black
//selected btn
//You can also set btn images by
//btn.setImage(<#T##image: UIImage?##UIImage?#>, for: <#T##UIControlState#>)
} else {
btn.backgroundColor = UIColor.red
//not selected btn
}
}
}
In iOS , you would have to do it manually.See the below approaches,
Use a switch . Using a UISwitch would be better if the option indicates a on/off state.
Use a same method when the button is pressed. Whenever the method gets called deselect the other button/buttons and select the pressed button. You can use tags or keep a reference of the buttons to differentiate between them.
Lastly , keep different methods for each buttons . Just deselect the other buttons whenever the button is pressed.
You can follow the above approaches by using interface builder or programmatically.
You can achieve it like below
I have implemented it for dates which are in TableView you just need to do little modifications
enum filterDateSelectableOptions:Int {
case AssignDate
case DueDate
case CompletionDate
}
//Assign Date selected by default
var currentSelectedFilterDate:filterDateSelectableOptions = .AssignDate
Now
func btnRadioButtonTapped(sender:UIButton) {
switch sender.tag {
case kTableViewRow.AssignDate.rawValue:
self.currentSelectedFilterDate = .AssignDate
case kTableViewRow.DueDate.rawValue:
self.currentSelectedFilterDate = .DueDate
case kTableViewRow.CompletionDate.rawValue :
self.currentSelectedFilterDate = .CompletionDate
default:
break;
}
//sender.isSelected = !sender.isSelected
self.tblFilterList.reloadData()
}
in cellForRow I have
// THIS IS DIFFERENT ENUM SO +1 is required in my case
case .AssignDate,.DueDate,.CompletionDate :
let button = buttonRadioCircle
button.tag = row.rawValue
cell.accessoryView = button
button.addTarget(self, action: #selector(btnRadioButtonTapped(sender:)), for: .touchUpInside)
button.isSelected = self.currentSelectedFilterDate.rawValue + 1 == row.rawValue
}

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

Creating a word game

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.

Resources