2016-04-06 86 views
0

在這裏寫一個示例應用程序來說明一些似乎不太正確的動畫行爲?我在屏幕的下半部分創建一個堆棧視圖,添加一個按鈕,將它移動到包括按鈕在內的屏幕上{它移動},但附加到按鈕的動作仍然在下半部分?堆棧視圖錯誤還是我錯過了什麼?

事實上,如果我看看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 
} 
} 

回答

1

您正在爲您的stackview的背景層設置動畫而不是stackview本身的框架。要爲堆棧視圖設置動畫效果,您可以使用UIView方法animateWithDuration:animations:併爲stackview的frame屬性設置動畫效果。爲了更好地瞭解現在發生的事情,您可以啓用selectSV.clipsToBounds = true到您的堆棧視圖。這樣,堆棧視圖的layer在離開框架時被剪切。

0

謝謝果凍!

註釋掉這...

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

,並取代其與此工程完美!

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

容易,當你知道如何......很多在這一領域的學習...