How to stop my UIButton animation SWIFT - swift

I made an animation with UIButton via somes images.
Here's the code:
#IBAction func Touchdown(sender: AnyObject) {
Izer.setImage(image1, forState: UIControlState.Normal)
Izer.imageView!.animationImages = [image1, image2, image3, image4, image5,
image6, image7,image8]
Izer.imageView!.animationDuration = 0.9
Izer.imageView!.startAnimating()
playButton.enabled = false
}
#IBAction func TouchUp(sender: AnyObject) {
soundRecorder.stop()
playButton.enabled = true
}
When I touch the button , the animation start. But I want to stop it via my Touchup function.
How can I do it ?
Thank you , and sorry for my bad english :(

Add this to your TouchUp func:
Izer.imageView!.stopAnimating()
p.s. A good place to find information about functions is in the Apple documentation - it really is quite good. So this is the page for an imageView and if you look on the left under tasks, or if you scroll down, you can see the functions and properties you can call and set for animating an imageView.

Ok, looks like you want the button to act as a toggle switch. On the first touch the button starts animating an imageview and records something. When touched again the animation stops and the button is enabled again.
You can achieve this by declaring a bool variable that tracks the state of the button. If the boolean value is set to true, you run the animation & recording. If the boolean value is false, you stop the and recording.
Here is the sample code :
class ViewController: UIViewController {
#IBOutlet weak var mainView: UIView!
var isButtonPressed = false{
// Adding a Property Observer, that reacts to changes in button state
didSet{
if isButtonPressed{
// Run the Recording function & Animation Function.
startAnimationAndRecording()
}else{
// Stop the Recoding function & Animation Function.
stopAnimationAndRecording()
}
}
}
#IBAction func changeButtonValue(sender: UIButton) {
// Toggle the button value.
isButtonPressed = !isButtonPressed
}
func startAnimationAndRecording(){
// Add your animation and recording code here.
}
func stopAnimationAndRecording(){
//Add your stop Animation & Stop Recording code here.
}
}

Related

How to prevent videoGravity changes in AVPlayerViewController

My memory is not working for me right now. I think I remember there was a way to prevent the video interface of AVPlayerViewController (or similar) from having the button which allows user to toggle between videoGravity settings, I think those are basically two;
.resizeAspect
.resizeAspectFill
User can also double tap on screen to toggle between these two.
What I'd like to do is force the video of a AVPlayerViewController to only use . .resizeAspect for .videoGravity. I think I remember there should be a way to do this with an easy boolean toggle somewhere, but cannot find it searching for 15 minutes.
Here's a very dirty way I was able to hide the button. Unfortunately, user can still use gestures (double tap, pinch) to zoom the video. The proper thing to do is a full custom view it seems.
e.g.
extension UIView {
var recursiveSubviews: [UIView] {
return subviews + subviews.flatMap { $0.recursiveSubviews }
}
}
class CustomPlayerViewController: AVPlayerViewController {
private func hideZoom() {
let zoomButton = view.recursiveSubviews.first(where: { $0.accessibilityLabel == "Zoom" })
zoomButton?.superview?.removeFromSuperview()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
hideZoom()
}
}

detect when button is pressed down and then up Swift macOS

I'm writing an app that send commands to a set top box.
The box can receive two types of commands: push and release.
I can get the button pressed on macOs in swift.
#IBAction func btnPressed(sender: NSButton) { } in which i send the command and the release. For any command such as change channel, mute or other, all works fine.
Instead, for volume up or done, I need, by doing what I do, to click several time to have the volume up or down.
I got the mouse up and down working, detecting where the click happened (inside the NSImageView (if not a button) corresponding to the up and down images) to simulate a long volume up or down press, but I can't get it inside the button pressed method.
is there a way in the 'buttonpressed' method to combine the mouse event in order to simulate a long press while holding the mouse down?
PS: I have googled and searched here also but did not find a hint.
if it can help:
1 subclass the button class to fire the action on mouseDown and mouseUp (the action will be fired twice)
class myButton: NSButton {
override func awakeFromNib() {
super.awakeFromNib()
let maskUp = NSEvent.EventTypeMask.leftMouseUp.rawValue
let maskDown = NSEvent.EventTypeMask.leftMouseDown.rawValue
let mask = Int( maskUp | maskDown ) // cast from UInt
//shortest way for the above:
//let mask = NSEvent.EventTypeMask(arrayLiteral: [.leftMouseUp, .leftMouseDown]).rawValue
self.sendAction(on: NSEvent.EventTypeMask(rawValue: NSEvent.EventTypeMask.RawValue(mask)))
//objC gives: [self.button sendActionOn: NSLeftMouseDownMask | NSLeftMouseUpMask];
}
}
2: in the storyboard, change the class of the NSButton to your class:
3: set the sender of the action to your subclass and check the currentEvent type:
#IBAction func volUpPressed(sender: myButton) {
let currEvent = NSApp.currentEvent
if(currEvent?.type == .leftMouseDown) {
print("volume Up pressed Down")
//... do your stuff here on mouseDown
}
else
if(currEvent?.type == .leftMouseUp) {
print("volume Up pressed Up")
//... do your stuff here on mouseUp
}
}

Adding long-press to a button while maintaining normal highlight behavior?

I have a button with a long-press gesture recognizer assigned to it.
I would like the button to remain highlighted (just as it would during a normal click) for the duration of a long press, AND for the single click NOT to be triggered after the long press.
What I have tried so far:
To illustrate why it might be important to have this functionality, let's take the example of a UILabel that displays a number, and a button that increments that number.
A single click should increment the number by 1, and a long-press should increment it by 10 (a timer could be added later that "auto-increments" the number as the finger is held down, but for the purposes of this example, I am leaving that out).
So I started with this code:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var numberDisplayLabel: UILabel!
#IBOutlet weak var incrementNumberButton: UIButton!
#IBOutlet var buttonLPGR: UILongPressGestureRecognizer!
var numVal = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
numberDisplayLabel.text = String(numVal)
}
#IBAction func buttonClicked(_ sender: UIButton) {
print("button clicked")
numVal += 1
numberDisplayLabel.text = String(numVal)
}
#IBAction func longPressOnButtonRecognized(_ sender: UILongPressGestureRecognizer) {
print("long press recognized, state: \(sender.state.rawValue)")
if (sender.state == .ended) {
numVal += 10
numberDisplayLabel.text = String(numVal)
}
}
}
Let's try to single click and see if that works:
Yes it does, YAY.
Now let's see what happens if we long-press it:
So... you can see that the button highlights when touched down (as normal), but when the long press is recognized (enters the .began state), the highlight is cancelled. When we finally release the touch, the number is incremented by 10 as expected.
But what if we want the button to remain highlighted during the entire process...
we could try adding this code to viewDidLoad():
buttonLPGR.cancelsTouchesInView = false
This should prevent the initial touch from being cancelled by the long-press recognition.
Let's see! :
Hmmm well we got what we wanted as far as the highlighting, but now, since the regular press is no longer cancelled by the long press, the button's touchUpInside action function is still called and so the number is incremented not only by 10, but by 1 also.
This is where I don't know what to do from this point.
So, once again: How can we have the button remain highlighted (just as it would during a normal click) for the duration of a long press, AND for the single click NOT to be triggered after the long press?
If the touch framework provides a way of doing this without a work-around, that would be preferred.

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

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