swift identify which button was pressed - ios

How to identify in swift if which button was pressed i have 3 button actions.now i have another button is which when pressed it will identify which button from the 3 was pressed. cause first is you have to click from the 3 button after clicking from the 3 button then you will click
idenfifywhichpressed button and this button will identify or print which button from the 3 was pressed.
//this button will identify
#IBAction func idenfifywhichpressed(_ sender: UIButton) {
}
the 3 buttons
#IBAction func btn1(_ sender: UIButton) {
}
#IBAction func btn2(_ sender: UIButton) {
}
#IBAction func btn3(_ sender: UIButton) {
}

Try something like this
Declare an enum
enum SelectedButtonTag: Int {
case First
case Second
case Third
}
Button Action
Connect the three button actions to this method with different tag
#IBAction func idenfifywhichpressed(sender: UIButton) {
switch sender.tag {
case SelectedButtonTag.First.rawValue:
print("do something when first button is tapped")
case SelectedButtonTag.Second.rawValue:
print("do something when second button is tapped")
case SelectedButtonTag.Third.rawValue:
print("do something when third button is tapped")
default:
print("default")
}
}

Small improvement on #prajnaranjan-das answer: casting to an enum immediately to clean up some cruft and remove the need to implement default in the switch...
enum ButtonTag: Int {
case First
case Second
case Third
}
func buttonTapped(_ sender: UIButton) {
guard let knownSender = ButtonTag(rawValue: sender.tag) else { return }
switch knownSender {
case .First:
print("do something when first button is tapped")
case .Second:
print("do something when second button is tapped")
case .Third:
print("do something when third button is tapped")
}
}

This is helped for me (swift 5.0)
#IBAction func hardnessSelected(_ sender: UIButton) {
print(sender.currentTitle) // <----------
}
}

Do something like this,
var index:Int = 0
Now do this, FYI, set button tags accordingly 1,2 and 3...
#IBAction func btn1(_ sender: UIButton) {
index = sender.tag
}
#IBAction func btn2(_ sender: UIButton) {
index = sender.tag
}
#IBAction func btn3(_ sender: UIButton) {
index = sender.tag
}
now this,
#IBAction func idenfifywhichpressed(_ sender: UIButton) {
if index == 1 {
//Button 1 Pressed
}else if index == 2 {
//Button 2 Pressed
} else if index == 3{
//Button 3 Pressed
}
}
FYI. You can use Switch statement as well in idenfifywhichpressed method.
Update. Do not create three methods for btn1, btn2 and btn3, just create one method and assign tag accordingly for simplicity.

I think you can take a variable like
var checkBtn: String?
inside 1st button change the variable value
checkBtn = "1"
inside 2nd button change the variable value
checkBtn = "2"
inside 3rd button change the variable value
checkBtn = "3"
#IBAction func idenfifywhichpressed(_ sender: UIButton) {
// just print the value of CheckBtn
print(checkBtn)
//this will give you which btn pressed right
}

Related

Indexes or tags? For multiple checkboxes as buttons in IBOutletCollection

I'm kind of new to swift, but someone mentioned that I should use indexes or tags for the buttons in an IBOutletCollection.
Im not sure how to index or tag specific buttons, and then reference them in the cases:
// images of checked and unchecked boxes for the button to switch between
var BoxON = UIImage(named: "CheckBox")
var BoxOFF = UIImage(named:"UnCheckBox")
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
boxes.forEach {
$0.setImage(BoxOFF, for: .normal)
$0.setImage(BoxON, for: .selected)
}
}
#IBOutlet var boxes : [UIButton]!
#IBAction func boxTouched(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
let index = boxes.index(of: sender)!
switch index {
case 0:
sender.isSelected = !sender.isSelected
case 1:
sender.isSelected = !sender.isSelected
case 2:
sender.isSelected = !sender.isSelected
case 3:
sender.isSelected = !sender.isSelected
case 4:
sender.isSelected = !sender.isSelected
default:
sender.isSelected = !sender.isSelected
}
}
Thanks in advance! :)
EDIT:
Removed the switch and replaced with an if statement (It Works!)
#IBAction func boxTouched(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
if sender.isSelected{
sender.setImage(BoxOFF, for: .normal)
sender.setImage(BoxON, for: .selected)
}
You click on each button in the storyboard and then set the tag in the Attributes inspector. This is something you should do because IBOutletCollections aren't guaranteed to maintain the order.
Then in your code you just access the tag like so: sender.tag
#IBAction func clickedButton(_ sender: UIButton) {
switch sender.tag {
case 0:
print("this is button 0")
case 1:
print("this is button 1")
case 2:
print("this is button 2")
default:
print("unknown button")
}
}
This works for me after ctrl+dragging each button to the method.
On storyboard you can set tag for every button in attribute inspector. Following is the altered code:
#IBAction func boxTouched(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
let buttonTag = sender.tag
switch tag {
case 0:
//code you want to write for case 0
case 1:
//code you want to write for case 1
case 2:
//code you want to write for case 2
case 3:
//code you want to write for case 3
case 4:
//code you want to write for case 4
default:
//code you want to write for default case
}
}

Change view controller using swipe gesture

I want to use swipe gesture to move to another view controller using right direction. Can you help me?
#IBAction func right(_ sender: UISwipeGestureRecognizer) {
// what I must write here
}
Just write one line code -
#IBAction func right(_ sender: UISwipeGestureRecognizer) {
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case UISwipeGestureRecognizerDirection.right:
self.performSegueWithIdentifier("nextView", sender: self)
break
default:
break
}
}
}

Swift: How to toggle two UI Switches

I have two UI Switches
When I tap one, I want the other to turn off and vice versa
Below I have two switch actions.
I've tried to check if switch one is on (which is by default) and if it is when tapped, then turn it off, but if it isn't on, then turn it on.
#IBAction func switchOnePressed(_ sender: UISwitch) {
if switchOne.isOn {
label.text = "UISwitch is ON"
switchOne.setOn(false, animated: true)
} else {
label.text = "UISwitch is OFF"
switchOne.setOn(true, animated: true)
}
}
#IBAction func switchTwoPressed(_ sender: UISwitch) {}
Any help would be great!
This simplifies things a lot by reducing the code required. The opposite switch is then set based off the current value of the calling switch.
#IBAction func switchOnePressed(_ sender: UISwitch) {
label.text = sender.isOn ? "UISwitch is ON" : "UISwitch is OFF"
switchTwo.setOn(!sender.isOn, animated: true)
}
#IBAction func switchTwoPressed(_ sender: UISwitch) {
label.text = sender.isOn ? "UISwitch is ON" : "UISwitch is OFF"
switchOne.setOn(!sender.isOn, animated: true)
}
You do not need to set the value for the calling switch since that should already be handled by the interface interaction.
Also, I don't know what your intention is with the label, but it would be misleading in its current form since it does not indicate what switch is on & off. Perhaps you have unique labels for each one, but that is just speculation on my part.

How to get the current Title of a button in Swift 3.0 , ios using sender.titleForState(.Normal)!

I tried to get the title of a button in swift like below.
#IBAction func buttonAction(_ sender: Any) {
let buttonTitle = sender.titleForState(.Normal)!
}
but it didn't work,even it doesn't give any hint when we press . after the sender.
so what is the correct way of doing this in swift 3.0
Or else if we create an IBOutlet and then we use its currentTitle, it works fine like below. Why we cannot get it with sender. for above
#IBOutlet var thebutton: UIButton!
#IBAction func buttonAction(_ sender: Any) {
let buttonTitle = thebutton.currentTitle!
print(buttonTitle)
}
Because parameter sender is in type Any instead of UIButton. Change the method signature to:
#IBAction func buttonAction(_ sender: UIButton) {
if let buttonTitle = sender.title(for: .normal) {
print(buttonTitle)
}
}
and you should be good to go.
Smartest version using Swift 5.0:
#IBAction func buttonAction(_ sender: UIButton) {
print(sender.currentTitle)
}
To get the title of the button regardless of its current state in swift 3.0 try using this:
#IBAction func buttonPressed(_ sender:UIButton){
let buttonTitle = sender.titleLabel?.text
print("\(String(describing: buttonTitle)")
}
This will return the title for the state, based on the state that the button is current in.
In order to resolve the warning, following code may be used.
#IBAction func buttonAction(_ sender: UIButton) {
let buttonTitle = sender.title(for: .normal) ?? String()
print(buttonTitle)
}
Using Swift version 5.5.2, the best way I found out to print a label's title is:
#IBAction func keyPressed(_ sender: UIButton) {
print(sender.title(for: .normal)!)
}
I was receiving a warning while using sender.title(for: .normal). The exclamation mark (!) solved it.
#IBAction func buttonPressed(_ sender: AnyObject) {
let title = sender.title(for: .normal)
print("\(title) button pressed")
}
So this is for swift 4.0, not the last one.
If your button has a regular title you can use:
button.title(for: state) // probably UIControl.State.normal
If your UIButton has an attributed title you'll need to use:
self.attributedTitle(for: state)
Or you can use a more general extension:
extension UIButton {
func titleForState(_ state: UIControl.State = .normal) -> String? {
if let title = self.title(for: state) {
return title
}
if let attribTitle = self.attributedTitle(for: state) {
return attribTitle.string
}
return nil
}
}
I used switch statment:
var buttonConter = 1
#IBAction func hardlessSelected(_ sender: UIButton) {
switch buttonConter {
case 1:
buttonConter += 1
print("Soft")
case 2:
buttonConter += 1
print("Medium")
case 3:
buttonConter += 1
print("Hard")
default:
print("Non")
}
}
}
The simple way just to use currentTitle:
#IBAction func hardlessSelected(_ sender: UIButton) {
print(sender.currentTitle)
}
Instead of using the currentTitle of the UIButton to get the name, you can use titleLabel.
The easy way to get this done is to unwrap the titleLabel then unwrap the text:
#IBAction func buttonAction(_ sender: UIButton) {
var buttonTitle = sender.titleLabel!.text!
print(buttonTitle)
}
Since Swift 3.0, it changed from
sender.titleForState(.Normal)! >> sender.title(for : .normal)!
Change Any to AnyObject.
#IBAction func buttonPressed(_ sender: AnyObject) {
let title = sender.title(for: .normal)!
print("\(title) button pressed")
}
#IBAction func btnNextTapped(_ sender: Any) {
let title = (sender as AnyObject).title(for: .normal)!
}
Swift4.0

Disabling a Button in Swift

So I'm new to Swift, but trying to figure out how to disable this button when it is pressed. I have the following:
#IBAction func IBbtnUpdateTap(sender: UIButton){
if imageNumber == 0 {
IBbtnUpdateTap.enabled = false
}
I'm not sure why it's giving me problems. Any ideas?
IBbtnUpdateTap isn't the button. The button is sender
#IBAction func IBbtnUpdateTap(sender: UIButton){
if imageNumber == 0 {
sender.enabled = false
}

Resources