简体   繁体   中英

Swift, animate to specific CGPoint

How could I animate programatically created object to go to a specific CGPoint. Not using CGAffineTransformMakeTranslation, as this is just on how to move it, not exactly where to move it.

I have tried: translatesAutoresizingMaskIntoConstraints = true

But it makes no difference.

I have tried this:

//Define screen sizes
let screenSize: CGRect = UIScreen.mainScreen().bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height

// Sizes of centre cards
let centreCardWidth = screenWidth/5
let centreCardHeight = (screenWidth/5) / 0.625
let centralizeViewHorizontalCard = (screenWidth/2) - ((screenWidth/5) / 2)
let centralizeViewVerticleCard = screenHeight / 2

UIView.animateWithDuration(0.25, delay: 0.5, options: [], animations: {
    centreCard3.frame = CGRectMake(centralizeViewHorizontalCard, centralizeViewVerticleCard, centreCard3.frame.size.width, centreCard3.frame.size.height)
    }, completion: nil)

But when run in the simulator, absolutely nothing happened.

Your UI hasn't rendered yet when you are animating. Put it in viewDidAppear. This works for me:

class ViewController: UIViewController {

    @IBOutlet weak var centreCard3: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewDidAppear(animated: Bool) {
        let screenSize: CGRect = UIScreen.mainScreen().bounds
        let screenWidth = screenSize.width
        let screenHeight = screenSize.height

        // Sizes of centre cards

        let centralizeViewHorizontalCard = (screenWidth/2) - ((screenWidth/5) / 2)
        let centralizeViewVerticleCard = screenHeight / 2

        UIView.animateWithDuration(0.5, delay: 0.5, options: [], animations: {
            self.centreCard3.frame = CGRectMake(centralizeViewHorizontalCard, centralizeViewVerticleCard, self.centreCard3.frame.size.width, self.centreCard3.frame.size.height)
            }, completion: nil)
    }
}

Result:

结果

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