How to create toggle button that only toggles once - swift

I want to create a button that, when pressed, toggles to a different format and stays that way, not allowing the user to toggle it back. For example, I am trying to create a button that says "Special 1" then when it is clicked by the user, it toggles to say "USED". When the word "USED" pops up on the UIButton, it stays that way and the user cannot change it back. Please help me out I can't figure this out. I am also open to other ideas to execute this other then a UIButton, for example maybe a UITableView??

What you can do is create a boolean (true or false) variable in your ViewController, and whenever the button is tapped you set this variable so that the tap function associated with the button can be manipulated.
1.) Make an action connection from your ViewController to your code this can be done by clicking the dual view button (the two circles in the top right corner) then holding control and drag your button into your code. :
For more information on connecting views to your code: https://codewithchris.com/9-hooking-it-all-up-swift-iboutlet-properties/
Skip to 6 min for the actual connection.
2.) Now we can just make our boolean variable, and make a basic if statement:
var didClick:Bool = false
#IBAction func touchButton(_ sender: UIButton) {
if !didClick { // If didClick is false
didClick = true // Set it to true
sender.setTitle("USED", for: .normal)
}
}
Note: The sender should be set to UIButton NOT Any
Should look like this:
_ sender: UIButton

If you are using a storyboard you can write this inside the IBAction function:
#IBAction func buttonName(_ sender: UIButton) {
sender.isUserInteractionEnabled = false
// Do whatever you need to do after...
}
sender's type could be UIButton or Any depending on how you made the connection from the storyboard.

Related

how to hide button title but can still call it using sender.currentTitle?

I added a button in the main storyboard in Xcode. This button has an image as the background and its title "blueDoor" is shown on top of the background (see photo below).
There will be three buttons like this and they are linked to one IBAction. I would like to use sender.currentTitle to let the program know which button is clicked, but I don't want the text to show on the image.
How can I hide the text but still keep the title attribute so sender.currentTitle can be used? Or is there another way to do so?
A button with an image as the background:
You can use tag to do this.
Open storyboard > select your button > select Show the Attributes Inspector section in the right bar of the Xcode > scroll down and find Tag under the View section. And give different tags to your buttons.
Then your IBAction should be like this ->
#IBAction func didTapMyButtons(_ sender: UIButton) {
switch sender.tag:
case 0: // it is your first button's tag
// Do something with button which has tag `0`
case 1: // it is your second button's tag
// Do something with button which has tag `1`
case 2: // it is your third button's tag
// Do something with button which has tag `2`
default: break
}
Shortly: you can not do that. The currentTitle property is essentially a getter for button.titleLable.text. So is title(for: UIControl.State) setter (setTitle(String?, for: UIControl.State))
What docs say:
var currentTitle: String? { get }
Discussion
The value for this property is set automatically whenever
the button state changes. For states that do not have a custom title
string associated with them, this method returns the title that is
currently displayed, which is typically the one associated with the
normal state. The value may be nil.
This means whatever changes you bring to titleLabel.text, it is automatically reflected on a currentTitle property.
You can use tags as suggested or add a custom action handler for every button as you create them. E.g. for cancel and proceed buttons one will do it like so:
self.cancelButton.addTarget(self, action: #selector(self.cancelActionMethod), for: .touchUpInside)
self.proceedButton.addTarget(self, action: #selector(self.proceedActionMethod), for: .touchUpInside)
And then somewhere inside self:
#objc func cancelActionMethod() {
// some cancel specific actions
}
#objc func proceedActionMethod() {
// some cancel specific actions
}

Hide button function if statement issue - Swift

I have a function to hide a slider if another button is pressed. I currently have:
#IBOutlet weak var sliderHide: UISlider!
#IBAction func sliderHide(sender: UISlider) {
if (buttonPlay.selected) {
sliderHide.hidden = false
}
else if (!buttonPlay.selected) {
sliderHide.hidden = true
}
}
The build is running but the slider only hides if itself is selected. It does nothing if the button is selected.
Use == not = when comparing,= is an assignment operator.
Moreover, if buttonImage is not a variable representing the control state of a button, but the button itself you want to do:
if buttonImage.selected == false {
}
However, you should use an #IBAction for the button if you want to run a function when it is pressed.
Please consider using an #IBAction for this kind of thing unless your button is programmatically created. You can read more about it here:
http://rshankar.com/different-ways-to-connect-ibaction-to-uibutton/
I
I think you want
add an Outlet to the slider like the picture and then wherever you play the sound, make the sliderYouMightHide.hidden = false and wherever the sound stops make the sliderYouMightHide.hidden = true. You might also want to make it hidden in viewDidLoad

How to determine which UIBarButtomSytemItem has been pressed

in a navigation controller i have 2 bar button items linked in the StoryBoard: 1 on the right with System Item = Add and 1 on the left with System Item = Cancel. Both buttons are linked to the same action. how can i determine which one has been triggered using a switch statement?
#IBAction func pressedBarButtonItem(sender: UIBarButtonItem) {
switch sender {
case UIBarButtonSystemItem.Add:
print("UIBarButtonSystemItem.Add button has been pressed ...")
default:
break
}
}
this causes an error "Enum case "Add" is not a member of type 'UIBarButtonItem'" so is there an Enum attribute to the bar button that says it is a system type?
thanks
UIBarButtonSystemItem is used only at initialization to define a system image, those are not styles or types and are not stored or affected to the button.
You may want to use tags or outlet references to select the right action, or use different IBActions, which seems more appropriate.
Give tag to both the UIBarButtonItems in storyborad.
Say Add have tag value 1001 and Cancel have tag value 1002.
Compare tags in you IBAction.
#IBAction func pressedBarButtonItem(sender: UIBarButtonItem) {
switch sender.tag {
case 1001:
print("UIBarButtonSystemItem.Add button has been pressed ...")
case 1002:
print("UIBarButtonSystemItem.Cancel button has been pressed ...")
default:
break
}
}

NSButton RadioGroup (NSMatrix Alternative)

I've tried a few times to set up several similar buttons, all connected to the same IBActions, and still can't seem to replicate the RadioButton Behaviour.
At the moment, I have 5 Buttons, all children of one NSView..
NSView
- ButtonOne - NSButton (Square Button)
- ButtonTwo - NSButton (Square Button)
- ButtonThree - NSButton (Square Button)
- ButtonFour - NSButton (Square Button)
- ButtonFive - NSButton (Square Button)
They're all connected to a common IBAction, which reads as:
#IBAction func activityButtonPressed(sender: NSButton) {
println("\(sender.title) Pressed")
}
Which works to the point where the actual mosueDown events are caught and sent to the func (as expected)..
how do I get them working in the Radio Button mode? i.e. have their NSOnState and NSOffState toggle when the various buttons are clicked?
When I try and change the button type to Radio Button, it automatically flips back to "Switch"....
Cheers,
A
just give the NSRadioButtons the same superview and action. And as noted by Good Doug in his answer,
[…] if you are using square button style, you can't use radio type. You want to use the On Off type in Interface Builder.
I really don't think you want to have your action method set the state of all buttons in the group… let AppKit do that for you.
From OS X Developer Release Notes: Cocoa Application Framework (10.10 and Earlier)
An NSButton configured as a radio button (with the -buttonType set to NSRadioButton), will now operate in a radio button group for applications linked on 10.8 and later. To have the button work in a radio group, use the same -action for each NSButton instance, and have the same superview for each button. When these conditions are met, checking one button (by changing the -state to 1), will uncheck all other buttons (by setting their -state to 0).
Since you specifically don't want to use NSMatrix...
First issue is that if you are using square button style, you can't use radio type. You want to use the On Off type in Interface Builder.
Here is the code I used for 4 buttons to test this out:
var buttonList : [NSButton] {
return [button1, button2, button3, button4]
}
#IBAction func buttonPressed(sender: NSButton) {
buttonList.forEach {
$0.state = $0 == sender ? .on : .off
}
}
As you can see, it iterates over all of the buttons, testing if it is the button that was pressed. It turns that button on while turning the other buttons off.
You will need to manage any state you want from there, or by checking the state of all of the buttons:
func whichButton() -> ActivityState {
if button1.state == .on { return .one }
if button2.state == .on { return .two }
...
}
where ActivityState.one is some enum case that you can use to determine which state you are in.
I believe that you are looking for NSMatrix:
You can configure this with as many rows and columns as you like:
You can then choose whether to allow a single choice or a variety:
You capture the selection in your IBAction with any combination of sender.selectedColumn and sender.selectedRow

Disable a Button

I want to disable a button (UIButton) on iOS after it is clicked. I am new to developing for iOS but I think the equivalent code on objective - C is this:
button.enabled = NO;
But I couldn't do that on swift.
The boolean value for NO in Swift is false.
button.isEnabled = false
should do it.
Here is the Swift documentation for UIControl's isEnabled property.
If you want the button to stay static without the "pressed" appearance:
// Swift 2
editButton.userInteractionEnabled = false
// Swift 3
editButton.isUserInteractionEnabled = false
Remember:
1) Your IBOutlet is --> #IBOutlet weak var editButton: UIButton!
2) Code above goes in viewWillAppear
The way I do this is as follows:
#IBAction func pressButton(sender: AnyObject) {
var disableMyButton = sender as? UIButton
disableMyButton.enabled = false
}
The IBAction is connected to your button in the storyboard.
If you have your button setup as an Outlet:
#IBOutlet weak var myButton: UIButton!
Then you can access the enabled properties by using the . notation on the button name:
myButton.enabled = false
Disable a button on Swift 3:
yourButton.isEnabled = false
For those who Googled "disable a button" but may have more nuanced use cases:
Disable with visual effect: As others have said, this will prevent the button from being pressed and the system will automatically make it look disabled:
yourButton.isEnabled = false
Disable without visual effect: Are you using a button in a case where it should look normal but not behave likes button by reacting to touches? Try this!
yourButton.userInteractionEnabled = false
Hide without disabling: This approach hides the button without disabling it (invisible but can still be tapped):
yourButton.alpha = 0.0
Remove: This will remove the view entirely:
yourButton.removeFromSuperView()
Tap something behind a button: Have two buttons stacked and you want the top button to temporarily act like it's not there? If you won't need the top button again, remove it. If you will need it again, try condensing its height or width to 0!
Swift 5 / SwiftUI
Nowadays it's done like this.
Button(action: action) {
Text(buttonLabel)
}
.disabled(!isEnabled)
You can enable/disable a button using isEnabled or isUserInteractionEnabled property.
The difference between two is :
isEnabled is a property of UIControl (super class of UIButton) and it has visual effects (i.e. grayed out) of enable/disable
isUserInteractionEnabled is a property of UIView (super class of UIControl) and has no visual effect although but achieves the purpose
Usage :
myButton.isEnabled = false // Recommended approach
myButton.isUserInteractionEnabled = false // Alternative approach
Let's say in Swift 4 you have a button set up for a segue as an IBAction like this #IBAction func nextLevel(_ sender: UIButton) {}
and you have other actions occurring within your app (i.e. a timer, gamePlay, etc.). Rather than disabling the segue button, you might want to give your user the option to use that segue while the other actions are still occurring and WITHOUT CRASHING THE APP. Here's how:
var appMode = 0
#IBAction func mySegue(_ sender: UIButton) {
if appMode == 1 { // avoid crash if button pressed during other app actions and/or conditions
let conflictingAction = sender as UIButton
conflictingAction.isEnabled = false
}
}
Please note that you will likely have other conditions within if appMode == 0 and/or if appMode == 1 that will still occur and NOT conflict with the mySegue button. Thus, AVOIDING A CRASH.
The button can be Disabled in Swift 4 by the code
#IBAction func yourButtonMethodname(sender: UIButon) {
yourButton.isEnabled = false
}
in order for this to work:
yourButton.isEnabled = false
you need to create an outlet in addition to your UI button.
Building on other answers here. I wanted to disable button for a few seconds to prevent double taps. Swift 5 version, xcode 13.4.1 likes this and has no warnings or errors.
#IBAction func saveComponent(_ sender: Any) {
let myButton = sender as? UIButton
myButton?.isEnabled = false
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(2000))
{
myButton?.isEnabled = true
}
}