2015-08-18 45 views
1

我一直在試圖讓這個snippit的代碼工作,但我似乎無法讓我的UIButton通過圖像進行動畫處理。在Swift中工作UIButton動畫

@IBOutlet weak var screenButton: UIButton!; 

func animation(){ 
     var animationButton : UIButton!; 
     var imageList = [UIImage](); 
     var image1:UIImage = UIImage(named:"3fingers-o-l-animation1.png")!; 
     var image2:UIImage = UIImage(named:"4fingers-o-l-animation1.png")!; 

     animationButtonscreenButton = screenButton; 
     imageList = [image1, image2]; 

     animationButton!.imageView!.animationImages = imageList; 
     animationButton!.imageView!.animationDuration = 1.0; 
     animationButton!.imageView!.startAnimating(); 
    } 

寫完這段代碼後,我從screenButton拖動了一個按鈕,我想通過故事板中的圖像設置動畫。 我在做什麼錯?

+2

UIButton未初始化... – Shoaib

+1

這就是爲什麼在適當的時候應該使用''''和'!'。不要「?」所有代碼,因爲它會隱藏錯誤。如果應該有什麼東西在那裏用武力解開'!'。或者在這種情況下只是一個非可選變量。你很早就會看到這個問題。 –

+1

i)初始化UIButton ii)設置它的框架iii)addSubview在你的視圖上 – Shoaib

回答

1

您需要做的是不要在函數animation中重新初始化UIButton;所以,註釋掉該行:

//var animationButton : UIButton! 

而且僅僅有一個IBOutlet,我們也是一個IBAction需要你的函數animation。通過控制拖動「行」到功能塊(請檢查IBAction,而不是IBOutlet),做與按鈕相同的操作。

一個小步行通過,而你仍然在故事板:


  • 你有什麼是隻有一個名爲按鈕:animationButton,這是從你的故事板的IBOutlet您通過控制拖動「行」來實現代碼。

  • 對於您的animation功能: 控制也從故事板從按鈕「行」拖動到animation功能塊。

  • 爲故事板設置一個初始圖像按鈕,這將在下面簡要提及。

此外,我們需要建立一個初始圖像中的故事板;否則,該按鈕的圖像屬性爲nil

請在右側的「屬性檢查器」中單擊故事板,然後設置圖像,在其中顯示「圖像」。作爲測試,我將其設置爲「1.jpg」。

因此,你的代碼看起來應該像下面這樣:

@IBOutlet weak var animationButton: UIButton! 
@IBAction func animation() 
{ 
    print("button touched") 
    //var animationButton : UIButton! 
    var imageList = [UIImage]() 
    var image1:UIImage = UIImage(named:"1.jpg")! 
    var image2:UIImage = UIImage(named:"2.jpg")! 

    //animationButtonscreenButton = screenButton; 
    imageList = [image1, image2]; 

    animationButton!.imageView!.animationImages = imageList 
    animationButton!.imageView!.animationDuration = 1.0 
    animationButton!.imageView!.startAnimating() 
} 

剛跑到一個快速測試;它會獲得觸摸事件和按鈕上的動畫圖像。希望這可以幫助。

+1

謝謝。在閱讀你的答案時,我發現我的代碼出了什麼問題。我的按鈕的圖像屬性爲零。在這個領域放置一個圖像解決了我的問題,我的屏幕現在變得瘋狂! –