swift UIView animateWithDuration с повтором и автореверсом

Я новичок в Swift, и это мой первый вопрос... Я хотел бы уменьшить шар продолжительностью 2 секунды, а затем увеличить его в течение 5 секунд. Моя проблема в том, что вторая продолжительность игнорируется (мяч сжимается в течение 2 секунд и растет в течение 2 секунд). Я надеюсь, что кто-то может помочь мне.

Это моя попытка:

    let ball = UIView()
    ball.frame = CGRectMake(50, 50, 50, 50)
    ball.backgroundColor = UIColor.blueColor()
    ball.layer.cornerRadius=25
    relaxContainer.addSubview(ball)

    UIView.animateWithDuration(2.0, delay:0, options: [.Repeat, .Autoreverse], animations: {
        ball.frame = CGRectMake(50, 50, 20, 20)
        }, completion: { finished in
            UIView.animateWithDuration(5.0, animations: {
                ball.frame = CGRectMake(50, 50, 50, 50)
            })
    })

person Syl    schedule 10.01.2016    source источник


Ответы (1)


Мой ответ благодаря помощи Мэтта (продолжительность, переменные исходного вопроса были изменены):

Свифт 2

let duration = 6.0
let delay = 0.0
UIView.animateKeyframesWithDuration(duration, delay: delay, options: [.Repeat], animations: {
    UIView.addKeyframeWithRelativeStartTime(0, relativeDuration: 1/3, animations: {
        ball.frame = CGRectMake(screenWidth/8*3, screenHeight/8*3, screenWidth/4, screenWidth/4)
    })
    UIView.addKeyframeWithRelativeStartTime(1/3, relativeDuration: 2/3, animations: {
        ball.frame = CGRectMake(screenWidth/4, screenHeight/4, screenWidth/2, screenWidth/2)
    })
    }, completion: nil
)

Свифт 3, 4, 5

let duration = 6.0
let delay = 0.0
UIView.animateKeyframes(withDuration: duration, delay: delay, options: [.repeat], animations: {
    UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 1/3, animations: {
        ball.frame = CGRect(x: screenWidth/8*3, y: screenHeight/8*3, width: screenWidth/4, height: screenWidth/4)
    })
    UIView.addKeyframe(withRelativeStartTime: 1/3, relativeDuration: 2/3, animations: {
        ball.frame = CGRect(x: screenWidth/4, y: screenHeight/4, width: screenWidth/2, height: screenWidth/2)
    })
    }, completion: nil
)
person Syl    schedule 11.01.2016
comment
Не забудьте обнулить свой блок завершения, если вы его не используете, чтобы ваш код оставался чистым :) - person Christopher Kevin Howell; 11.01.2016