Problems about draggable button over UICollectionView - ios

I’ve created a draggable button over an UICollectionView, and it works well. However, whenever I pull down the UICollectionView to update data, the draggable button would always be back to the original coordinate.
On the other hand, I also want to set a timer for the draggable button title, it means the title will be updated every second. But the draggable button would be back to original coordinate as well when the title is changed.
I’ve tried to use millisecond for the timeInterval, but it wastes more CPU and battery consumption. So I’d like ask if there’s any better way to deal with it?
【Update】
I recreate another project for this, please refer to the gif as below.
I place the button at the middle of the view, and the title will be added 1 every second. So I was wondering why the button always get back to the original coordinate whenever the title is changed.
Gif Here!
【Second Update】
I set constraints for the button, and use UIPanGestureRecognizer to change the position of the button. Please refer to the following code.
private func setupFloatingBtn() {
view.addSubview(self.floatingBtn)
self.floatingBtn.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
self.floatingBtn.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true
self.floatingBtn.widthAnchor.constraint(equalToConstant: 60).isActive = true
self.floatingBtn.heightAnchor.constraint(equalToConstant: 60).isActive = true
self.floatingBtn.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(handler)))
}
#objc func handler(gesture: UIPanGestureRecognizer) {
let location = gesture.location(in: self.view)
let draggedView = gesture.view
draggedView?.center = location
if gesture.state == .ended {
if self.floatingBtn.frame.midX >= self.view.layer.frame.width / 2 {
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseIn, animations: {
self.floatingBtn.center.x = self.view.layer.frame.width - 40
}, completion: nil)
}else{
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseIn, animations: {
self.floatingBtn.center.x = 40
}, completion: nil)
}
}
}

Related

Animate Constraint Relative to Another One

I setup an animation to hide one switch/label when another one is turned on. Simultaneously the switch that was just turned on move up. This works great with the simple explanation here.
However, when I try to move the switch/label back down after it is turned off it doesn't budge. The other switch reappears fine, but the top constraint change doesn't fire.
I'm relatively new to doing this type of setup and animating all programmatically and after spending an hour on this I'm stumped. Is it because I'm animating a top constraint relative to another one? How does that matter if it works the first time around? Even though the alpha of the hidden switch is set to zero, its frame is still there, right? Or am I doing something simple stupidly?
// Works Perfectly!
func hideVeg() {
self.view.layoutIfNeeded()
UIView.animate(withDuration: 1, delay: 0, options: [.curveEaseIn], animations: {
self.vegetarianSwitch.alpha = 0
self.vegetarianLabel.alpha = 0
self.veganSwitch.topAnchor.constraint(equalTo: self.vegetarianSwitch.bottomAnchor, constant: -30).isActive = true
self.view.layoutIfNeeded()
})
}
// Showing the label and switch works, but the topAnchor constraint never changes!
func showVeg() {
self.view.layoutIfNeeded()
UIView.animate(withDuration: 1, delay: 0, options: [.curveEaseIn], animations: {
self.vegetarianSwitch.alpha = 1
self.vegetarianLabel.alpha = 1
// This is the constraint that doesn't change.
// This is exactly what it was set to before the other hideVeg() runs.
self.veganSwitch.topAnchor.constraint(equalTo: self.vegetarianSwitch.bottomAnchor, constant: 40).isActive = true
self.view.layoutIfNeeded()
})
}
The issue here is that you are not modifying the constraints but actually creating new constraints with each animation. What you want to do instead is just create the constraint once (you can do it in code or in Interface Builder and drag and outlet). You can then just change the .constant field of the existing constraint in your animation block.
The constant needs to be changed with the animation, not creating an entirely new constraint. The old constraint still exists causing the issue.
var veganTopConstraint = NSLayoutConstraint()
// Top Constraint set up this way so it can be animated later.
veganTopConstraint = veganSwitch.topAnchor.constraint(equalTo: vegetarianSwitch.bottomAnchor, constant: 40)
veganTopConstraint.isActive = true
func hideVeg() {
UIView.animate(withDuration: 1, delay: 0, options: [.curveEaseIn], animations: {
self.vegetarianSwitch.alpha = 0
self.vegetarianLabel.alpha = 0
self.veganTopConstraint.constant = -30
self.view.layoutIfNeeded()
})
}
func showVeg() {
self.view.layoutIfNeeded()
UIView.animate(withDuration: 1, delay: 0, options: [.curveEaseIn], animations: {
self.vegetarianSwitch.alpha = 1
self.vegetarianLabel.alpha = 1
self.veganTopConstraint.constant = 40
self.view.layoutIfNeeded()
})
}

How to move UITableViewCell back and forth to show it can be swiped?

I see in some apps when you come to a screen with a tableview there's a short animation of the cell starting to be swiped, showing the red "swipe to delete" button (UIContextualAction button) and then it returns to normal. It is giving the user the hint: "These rows can be swiped."
Is there a way to achieve this effect? Maybe a way to programmatically start a row swipe then cancel it?
Swift Solution
Well, about 1.5 years later I finally came up with a solution.
Step 1 - Cell UI Setup
I set up my custom table view cell like this:
A and B represent the swipe action colors.
C is the UIView that I will animate side-to-side.
Step 2 - Add Animation to Cell
func animateSwipeHint() {
slideInFromRight()
}
private func slideInFromRight() {
UIView.animate(withDuration: 0.5, delay: 0.3, options: [.curveEaseOut], animations: {
self.cellBackgroundView.transform = CGAffineTransform(translationX: -self.swipeHintDistance, y: 0)
self.cellBackgroundView.layer.cornerRadius = 10
}) { (success) in
UIView.animate(withDuration: 0.2, delay: 0, options: [.curveLinear], animations: {
self.cellBackgroundView.transform = .identity
}, completion: { (success) in
// Slide from left if you have leading swipe actions
self.slideInFromLeft()
})
}
}
private func slideInFromLeft() {
UIView.animate(withDuration: 0.5, delay: 0, options: [.curveEaseOut], animations: {
self.cellBackgroundView.transform = CGAffineTransform(translationX: self.swipeHintDistance, y: 0)
}) { (success) in
UIView.animate(withDuration: 0.2, delay: 0, options: [.curveLinear], animations: {
self.cellBackgroundView.transform = .identity
})
}
}
Step 3 - Trigger the Animation
In the viewDidLoad of the view controller that has the table view, I have this code:
if self.tableView.visibleCells.count > 0 {
let cell = self.tableView.visibleCells[0] as! TableViewCell
cell.animateSwipeHint()
}
Example:
Video Solution
I created a video if you'd like a more in-depth walkthrough of this solution:
https://youtu.be/oAGoFd_GrxE
I have a piece of code that I saw long time ago to animate a view. Since our UITableViewCell is also a view, we can use it :) You just need to get your visible cell to animate, like so:
if let visibleCell = self.tableView.cellForRow(at: IndexPath(row: 0, section: 0)) as? CustomCell {
print("Started animation...")
let animation = CAKeyframeAnimation(keyPath: "transform.translation.x")
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.duration = 0.6
animation.values = [-20.0, 20.0, -20.0, 20.0, -10.0, 10.0, -5.0, 5.0, 0.0 ]
visibleCell.layer.add(animation, forKey: "shake")
}
Let me know if this helps. Tested it.
EDIT:
Animating your UITableView to let the user see that they can swipe on a cell is pretty easy, try it like so:
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) {
self.tableView.setEditing(true, animated: true)
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) {
self.tableView.setEditing(false, animated: true)
}
}
HOWEVER, if you want to swipe programmatically your cell to show your custom row actions, (I've been researching this for an hour), you can only achieve this, as far as I know, by using method swizzling. See this SO answer: http://codejaxy.com/q/186524/ios-swift-uitableview-how-to-present-uitableviewrowactions-from-pressing-a-button

UIView Animation sliding from below screen to bottom of screen

I programmatically created a UIStackView, which consists of two UICollectionView stacked vertically. One of them is a menubar, and one of them is a grid that displays media content.
let contentStack = UIStackView()
contentStack.addArrangedSubview(menuBar)
contentStack.addArrangedSubview(grid)
self.view.addSubview(contentStack)
I want the UIStackView to appear at the bottom of the screen, once a button is tapped. However, when it appears, I want it to do an animation, so it slides up from below the screen. I have looked at older solutions to posts similar to mine, but I could not find anything helpful because I manually set the constraints like this:
contentStack.translatesAutoresizingMaskIntoConstraints = false
contentStackBotAnchor = contentStack.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0)
contentStackBotAnchor!.isActive = true
contentStack.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
contentStack.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
contentStack.axis = .vertical
contentStack.spacing = 0
I have attempted solutions like such:
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseIn, animations: {
self.contentStack.frame = CGRect.init(x: 0, y: self.view.frame.height - self.contentStack.frame.height, width: self.contentStack.frame.width, height: self.contentStack.frame.height)
}, completion: nil)
This didn't work for me.
As Reinier stated, you can animate your constraints. Another option could be using a CGAffineTransform. When the view loads, simply change the y value of your UIStackView with something like:
contentStack.transform = CGAffineTransform(translationX: 0, y: view.frame.height)
And then when you want to animate it, use the animation of your choice:
UIView.animate(withDuration: 0.5, animations: {
contentStack.transform = .identity
})
This is what I prefer in such cases, hope it helps.
If you are using constraint then you must animate using your constraints, Try with this, I am not sure about the values but must be like this
self.view.layoutIfNeeded()
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseIn, animations: {
contentStackBotAnchor.constant = (self.contentStack.bounds.size.height * -1)
self.view.layoutIfNeeded()
}, completion: nil)
Hope this helps

Perfect Swift3 Boing

To animate a bar opening...
#IBOutlet var barHeight: NSLayoutConstraint!
barHeight.constant = barShut?30:100
self.view.layoutIfNeeded()
t = !barShut?30:100
UIView.animate(withDuration: 0.15,
delay: 0,
options: UIViewAnimationOptions.curveEaseOut,
animations: { () -> Void in
self.barHeight.constant = t
self.view.layoutIfNeeded()
},
completion: {_ in
Screen.barShut = !Screen.barShut
}
)
That's great ...
But how would you make it boing like this?
(The only way I'd know to do this is, use CADisplayLink, with a few lines of code for a spring decaying.) Is this available in UIKit?
You can use the spring animation method that is built in to UIView:
func toggleBar() -> Void {
self.view.layoutIfNeeded()
let newHeight:CGFloat = !barShut ? 30:100
barShut = !barShut
barHeightConstraint.constant = newHeight
UIView.animate(withDuration: 1.5, delay: 0, usingSpringWithDamping: 0.2, initialSpringVelocity: 3, options: [], animations: {
self.view.layoutIfNeeded()
}, completion: nil)
}
You will want a longer animation duration than 0.15 of a second in order for the bounce to seem realistic; I think the values I have look pretty good, but you can play with them to get the exact effect you are after.
Since the animation duration is longer, I found that I could tap the button the triggered the open/shut while the previous animation was still running. Setting barShut in the completion block meant that the bar didn't react to all taps. I moved the toggle outside of the animation to address this.

Take control of scrollView mid animation of contentOffset

When I tap my scrollView it activates a UITapGestureRecognizer that animates the contentOffset for about 2 seconds. How could I allow the user to interrupt the animation and take full control of the scrollView again when they drag? Right now the user has to wait until the end of the animation to start interacting with the scrollView again.
Note: self refers to the scrollView
Tap set up:
let singleTap = UITapGestureRecognizer(target: self, action: "subtleBounce:")
singleTap.cancelsTouchesInView = false
self.addGestureRecognizer(singleTap)
So when the user taps:
func subtleBounce(gesture : UITapGestureRecognizer) {
let originalFrame = self.frame
UIView.animateWithDuration(0.1, delay: 0.0, usingSpringWithDamping: 1.5, initialSpringVelocity: 1.5, options: UIViewAnimationOptions.CurveLinear, animations: {
self.contentOffset.y -= 10.0
}, completion: {
Void in
UIView.animateWithDuration(0.6, delay: 0.0, usingSpringWithDamping: 0.1, initialSpringVelocity: 3.0, options: UIViewAnimationOptions.CurveLinear, animations: {
self.contentOffset.y += 10.0 }, completion: { Void in
})
})
}
So the code above works as intended.
Here is what I've tried to stop the animation and give the user control of the scrollView again:
let drag = UISwipeGestureRecognizer(target: self, action: "stopScrollAnimation:")
drag.cancelsTouchesInView = false
self.addGestureRecognizer(drag)
and elsewhere:
func stopScrollAnimation(gesture : UISwipeGestureRecognizer) {
self.layer.removeAllAnimations()
self.setContentOffset(CGPoint(x: 0.0, y: 0.0), animated: false)
}
However this DOES NOT work as intended. The animation still controls the scrollView and the user cannot interact with it.
If you want an example what I mean, look at the iOS7/8 lockscreen. After tapping the screen it also starts an animation. The user can take control of the scrollView mid animation however.
edit: accepting answers in swift or obj-c.
Add AllowUserInteraction to your animation options.

Resources