2016-08-19 39 views
10

如何在每次單擊按鈕時將UIButton旋轉90度並同時跟蹤每個旋轉的位置/角度?每次單擊按鈕時將UIButton旋轉90度

這裏是我到目前爲止的代碼,但它只能旋轉一次:

@IBAction func gameButton(sender: AnyObject) { 
    UIView.animateWithDuration(0.05, animations: ({ 
     self.gameButtonLabel.transform = CGAffineTransformMakeRotation(CGFloat(M_PI_2)) 
    })) 
} 

回答

12
self.gameButtonLabel.transform = CGAffineTransformMakeRotation(CGFloat(M_PI_2)) 

應改爲

// Swift 3 - Rotate the current transform by 90 degrees. 
self.gameButtonLabel.transform = self.gameButtonLabel.transform.rotated(by: CGFloat(M_PI_2)) 

// OR 

// Swift 2.2+ - Pass the current transform into the method so it will rotate it an extra 90 degrees. 
self.gameButtonLabel.transform = CGAffineTransformRotate(self.gameButtonLabel.transform, CGFloat(M_PI_2)) 

隨着CGAffineTransformMake...,您創建一個全新的改造和覆蓋任何已經在按鈕上的變換。由於您想要將90度追加到已存在的變換(可能已旋轉0,90等角度),因此您需要添加到當前變換中。我給出的第二行代碼將做到這一點。

+0

的夫特版本3給出一個錯誤:類型的值「CGAffineTransform」沒有成員「」旋轉 AND 的夫特2.2+版本提供一個錯誤:額外的參數中請致電 – nodyor90z

+0

嗯。你在哪個Xcode測試版上?他們不斷更改所有方法名稱。我認爲我發佈的代碼來自Xcode 8 beta 5. – keithbhunter

+0

我還沒有升級到Xcode 8 beta。我目前使用的是Xcode 7.3.1,但在編寫我的代碼時,我仍然從Xcode獲得了Swift 3自動更正建議。 – nodyor90z

0

夫特4:

@IBOutlet weak var expandButton: UIButton! 

var sectionIsExpanded: Bool = true { 
    didSet { 
     UIView.animate(withDuration: 0.25) { 
      if self.sectionIsExpanded { 
       self.expandButton.transform = CGAffineTransform.identity 
      } else { 
       self.expandButton.transform = CGAffineTransform(rotationAngle: -CGFloat.pi/2.0) 
      } 
     } 
    } 
} 

@IBAction func expandButtonTapped(_ sender: UIButton) { 
    sectionIsExpanded = !sectionIsExpanded 
}