堆栈视图错误或我错过了什么?

时间:2016-04-06 07:19:10

标签: ios swift animation layer

在这里编写一个示例应用来说明一些似乎不太合适的动画行为?我在屏幕的下半部分创建一个堆栈视图,为它添加一个按钮,动画它将它移动到屏幕上{它移动}包括按钮,但是附加到按钮的动作仍然在下半部分?

的确,如果我查看Xcode上的调试器,它根本就没有移动过。

我在这里错过了一些动作?是?

import UIKit

class ViewController: UIViewController {

var selectSV: UIStackView!
var goNorth:CABasicAnimation!

override func viewDidLoad() {
    super.viewDidLoad()
    selectSV = UIStackView(frame: CGRect(x: 256, y: 696, width: 256, height: 196))
    selectSV!.axis = .Vertical
    selectSV!.spacing = 4.0
    selectSV!.alignment = .Center
    selectSV!.distribution = .FillEqually

    let zeroRect = CGRect(x: 0,y: 0,width: 0,height: 0)
    let newB = UIButton(frame: zeroRect)
    newB.setTitle("Blah", forState: UIControlState.Normal)
    newB.titleLabel!.font = UIFont(name: "Palatino", size: 24)
    newB.frame = CGRect(x: 0, y: 0, width: 128, height: 32)
    newB.addTarget(self, action: #selector(ViewController.blahblah(_:)), forControlEvents: .TouchUpInside)
    newB.backgroundColor = UIColor.blueColor()

    self.selectSV.addArrangedSubview(newB)
    self.view.addSubview(selectSV)
    NSTimer.scheduledTimerWithTimeInterval(4.0, target: self, selector: #selector(ViewController.moveSV), userInfo: nil, repeats: false)
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func blahblah(sender: AnyObject) {
    print("You hit me!")
}

func moveSV() {
    self.animateNorth()
    self.selectSV.layer.addAnimation(self.goNorth, forKey: nil)
}

func animateNorth() {
    goNorth = CABasicAnimation(keyPath: "position.y")
    goNorth.fromValue = 792
    goNorth.toValue = 288
    goNorth.duration = 4.0
    goNorth.delegate = self
    goNorth.setValue("window", forKey:"goNorth")
    goNorth.removedOnCompletion = false
    goNorth.fillMode = kCAFillModeForwards
}
}

2 个答案:

答案 0 :(得分:1)

您正在为stackview的支持层设置动画,而不是stackview本身的框架。要为stackview设置动画,您可以使用UIView方法animateWithDuration:animations:并为stackview的frame属性设置动画。要更好地了解现在发生的情况,您可以启用selectSV.clipsToBounds = true到您的堆栈视图。这样,堆栈视图的layer在离开帧时会被剪裁。

答案 1 :(得分:0)

谢谢果冻!

注释掉这个......

 self.animateNorth()
 self.selectSV.layer.addAnimation(self.goNorth, forKey: nil)

并将其替换为完美无缺!!

UIView.animateWithDuration(0.5, animations: {
                            self.selectSV.center.y = 288.0
                        })

当你知道如何在这个领域学到很多东西时很容易......