简体   繁体   中英

Making my UIView animate in the other direction when it hits the window's bound

I was wondering if there was an easier way to allow my view to animate in the opposite direction when the frames of my view go off the window whilst animating.

I was thinking of doing something like:

let x = CGFloat(Int(arc4random_uniform(UInt32(self.view.frame.maxX))))
let y = CGFloat(Int(arc4random_uniform(UInt32(self.view.frame.maxY))))
let label = UILabel(frame: CGRectMake(x,y, 50, 50))
label.text = "omnomnom"
label.sizeToFit()
let animateTimer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: #selector(animateLabel), userInfo: nil, repeats: true)

Where animateLabel is:

// Assuming that I have an instance variable of the label
if(label.layer.presentationLayer()?.frame.minX <= self.frame.minX
   && label.layer.presentationLayer()?.frame.maxY <= self.frame.maxY) {
    // Then grow in every direction but the left direction 
}
else if (label.layer.presentationLayer()?.frame.minX <= self.frame.minX) {
    // Then grow in every direction but the left direction bottom direction
}
...

But which CGAfflineTransform should I be using to specify transforms in these direction there are so many but I can't seem to find the correct one.

Also, is there a cleaner way to do this via some Core Animation API? Or is this the only way?

EDIT: So it seems like my question was misinterpreted, I want the view to grow as in doing something like CGAfflineTransformMakeScale(2,2) . But doing this would result to the label going off screen if it appeared near the edge of the window. So I was wondering whether there is a CG API that I could use so that I wouldn't have to check the frame of my label every time before determining which way it should grow

I would suggest doing a UIView keyframe animation. (Using the UIView animateKeyframesWithDuration:delay:options:animations:completion: method.)

You could set up a series of keyframes that would move your view to first one edge of the window, then the other.

I have a project called KeyframeViewAnimations on Github that demonstrates both UIView keyframe animation and the equivalent Core Animation technique.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM