2

I have a function in my UIView subclass. This function adjust the layout of the view.

For example

func addItemAtIndex(index: Int){
    // layout the view
    item[index].frame.size = view.frame.size
}

I can call myView.addItem(5) as normal.

Since this function adjust the view's layout, I can also call this function inside UIView's animation block. And it will layout the view with animation.

Like this,

UIView.animateWithDuration(0.3){
    myView.addItem(5)
}

However, I want to do the different behaviour when it's animated. Is it possible to check if the function get called inside UIView's animation block ?

Like this,

func addItemAtIndex(index: Int){
    if insideUIViewAnimationBlock{
        // layout with animation
    }else{
        // layout
    }
}

I'm not looking for addItemAtIndex(index: Int, animated: Bool) approach.

nRewik
  • 8,958
  • 4
  • 23
  • 30
  • You subclassed ít, so you can add a method like `addItemWithAnimationAtIndex:` do the same thing as addItemAtIndex, plus some custom command, and call it in animation block? – kientux Oct 24 '15 at 13:18
  • Yes, I can. but I'm looking for cleaner code, so that I can call only one function, regardless of being call inside or outside `UIView`'s animation block. – nRewik Oct 24 '15 at 13:34
  • @RMenke. Yes, I agree. But I think about the ease of use. So there will be only one function to remember. And then use animation block, as we animate things in iOS. – nRewik Oct 24 '15 at 13:48
  • 2
    I think you can't do that without passing an argument or use another function. Only one way I can think about is that UIView animation runs on main thread, so if you call your function on another thread, you can do some thread checks. But that's too complicated. – kientux Oct 24 '15 at 13:49
  • Possible duplicate of [how to tell if uiview is in middle of animation?](http://stackoverflow.com/questions/5526476/how-to-tell-if-uiview-is-in-middle-of-animation) – Senseful Oct 31 '15 at 00:58

1 Answers1

0

CALayer associated with the UIView is disabled implicit animation by default. It will be reenable inside an animation block. You can know whether inside or outside animation block to use that.

print("Outside animation block: \(self.view.actionForLayer(self.view.layer, forKey: "position"))")

UIView.animateWithDuration(5) { () -> Void in
    print("Inside animation block: \(self.view.actionForLayer(self.view.layer, forKey: "position"))")
}

For more information: https://www.objc.io/issues/12-animations/view-layer-synergy/

kishikawa katsumi
  • 10,418
  • 1
  • 41
  • 53