GDog
GDog

Reputation: 117

Center of button in scrollview

I wanted to make an animation where a pulse is being created when you hit a button. But that doesn't really work on a scrollview because it turns out to be a specific point on the 'screen', not on the scrollview. When you're scrolling down, the origin of the pulse stays the same.

@objc func addPulse() {
    let pulse = Pulsing(numberOfPulses: 1, radius: 120, position: playButton.center)
    pulse.animationDuration = 0.8
    pulse.backgroundColor = UIColor.red.cgColor

    self.view.layer.insertSublayer(pulse, below: playButton.layer)

The position has to be from the type CGPoint.

Upvotes: 1

Views: 368

Answers (2)

Samuel Cortez
Samuel Cortez

Reputation: 158

By the little amount of context you gave, I am gonna go ahead and assume you have a button inside a UIScrollView and you need to add a pulse animation behind the button but the problem is that as the view scrolls and the button changes its position the animation keeps appearing at the same position. Also, I suppose you're inside an UIViewController class.

If I'm completely right with my guesses this is what I think it's happening:

  • The position of playButton will always be the same since it is its position against its parent, in this case, the UIScrollView. The absolute position would be the position of the item in the screen.
  • You are adding the animation inside of the UIView (of the UIViewController) instead of the UIScrollView itself. This will be a problem while scrolling.

My suggestion is for you to try:

@objc func addPulse() {
     let pulse = Pulsing(numberOfPulses: 1, radius: 120, position: playButton.center)
     pulse.animationDuration = 0.8
     pulse.backgroundColor = UIColor.red.cgColor

     scrollView.layer.insertSublayer(pulse, below: playButton.layer)
}

Upvotes: 0

Christian Abella
Christian Abella

Reputation: 5797

If you are using a ScrollView, better use the center of the scrollview instead of the center of the button as the button will disappear as you scroll. So when you create the Pulsing object , use the self.view.center as position.

@objc func addPulse() {
    let pulse = Pulsing(numberOfPulses: 1, radius: 120, position: self.view.center)
    pulse.animationDuration = 0.8
    pulse.backgroundColor = UIColor.red.cgColor

    self.view.layer.insertSublayer(pulse, below: playButton.layer)
}

Upvotes: 1

Related Questions