如何在iOS中移动生动的文本?

时间:2016-04-12 08:23:31

标签: ios swift uilabel uivisualeffectview uiblureffect

我想制作一个在视图中心打招呼的应用程序,等待几秒钟并动画到顶部(有点像你在许多应用程序中看到的登录视图)

无论我尝试什么,我都无法将文字保持在x轴的中心位置。你能看一下我的代码并说出错误是什么吗?

谢谢

    // Blur Effect
    var blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Light)
    var blurEffectView = UIVisualEffectView(effect: blurEffect)
    blurEffectView.frame = view.bounds
    view.addSubview(blurEffectView)

    // Vibrancy Effect
    var vibrancyEffect = UIVibrancyEffect(forBlurEffect: blurEffect)
    var vibrancyEffectView = UIVisualEffectView(effect: vibrancyEffect)
    vibrancyEffectView.frame = view.bounds

    // Add label to the vibrancy view

    vibrancyEffectView.contentView.addSubview(vibrantLabel)

    vibrantLabel.textAlignment = NSTextAlignment.Center


    // Add the vibrancy view to the blur view
    blurEffectView.contentView.addSubview(vibrancyEffectView)


    UIView.animateWithDuration(1, delay: 1, options: .CurveEaseIn, animations: {() -> Void in

        self.vibrantLabel.frame = CGRectMake(0, 100, self.vibrantLabel.frame.width, self.vibrantLabel.frame.height)
        }, completion: {(finished: Bool) -> Void in
            self.view.alpha = 1
    })

2 个答案:

答案 0 :(得分:0)

要解决您的问题,请在动画期间保留标签的x原点。 请试试这一行:

self.vibrantLabel.frame = CGRectMake(self.vibrantLabel.frame.origin.x, 100, self.vibrantLabel.frame.width, self.vibrantLabel.frame.height)

您正在将x轴上的原点设置为零,因此您的标签动画左侧与其父视图对齐。

答案 1 :(得分:0)

找到解决方案。我需要在viewDidLayoutSubviews()中设置初始位置,然后在viewDidAppear()中设置动画

@IBOutlet var vibrantLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    // Blur Effect

    var blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Light)
    var blurEffectView = UIVisualEffectView(effect: blurEffect)
    blurEffectView.frame = view.bounds
    view.addSubview(blurEffectView)

    // self.vibrantLabel.layer.anchorPoint = (CGPointMake(-0.25, -2.65))

    // Vibrancy Effect
    var vibrancyEffect = UIVibrancyEffect(forBlurEffect: blurEffect)
    var vibrancyEffectView = UIVisualEffectView(effect: vibrancyEffect)
    vibrancyEffectView.frame = view.bounds

    // Add label to the vibrancy view

    view.addSubview(vibrantLabel)

    vibrantLabel.textAlignment = NSTextAlignment.Center

    // Add the vibrancy view to the blur view
    blurEffectView.contentView.addSubview(vibrancyEffectView)

}

override func viewDidLayoutSubviews() {


    vibrantLabel.center = CGPointMake(view.frame.midX, view.frame.midY)

}

override func viewDidAppear(animated: Bool) {

    UILabel.animateWithDuration(1.25, delay: 1, options: .CurveEaseInOut, animations: {

        self.vibrantLabel.center = CGPointMake(self.view.frame.midX, 100)

        }) { (Bool) in

            print("success")

    }


}