brkr brkr - 2 years ago 148
Swift Question

How to insert Custom Label with text into View with Animation?

Im making a small boxing app. This whole week iv been trying to work out how to solve my current problem above, with no luck :(.


Basically Its a 1 v 1 game. Each time the user hits the other player I want to make a tiny number pop up near him and float up and dissappear.

Its sort of like when you play MMORPG's and when you do dmg you see how much you did. See image below for an example!


So basically everytime the user hits the other player I want a little number to pop up on the screen to show the dmg and then float up and disappear.


  1. I am building the game on a simple UIView

  2. The label is a UILabel

Anywhere How I can achieve this?

Thank you!

Answer Source

Create a label, then use UIView.animateWithDuration to animate it.

    let label = UILabel(frame: CGRect(origin: point/*The point where you want to add your label*/, size: CGSize(width: 50, height: 50)))
    label.text = "+1"
    label.font = UIFont()//Your font
    label.textColor = UIColor.blueColor()
    label.alpha = 1

    UIView.animateWithDuration(1) { = CGPoint()//The point where you want your label to end up
        label.alpha = 0

Edit: As mentioned in the comments, you asked for how to create the label at a random point. Try this:

    let screenWidth = self.view.frame.width
    let screenHeight = self.view.frame.height

    let randomX = CGFloat(arc4random_uniform(UInt32(screenWidth)))
    let randomY = CGFloat(arc4random_uniform(UInt32(screenHeight)))

    let point = CGPoint(x: randomX, y: randomY)

As you will notice, for the width and height, I use the view's frame's width and height. You may want to use the view's bounds. For more on this, check out this SO Post.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download