セグメント化されたコントロールがあり、コントロールの右側がタップされている場合は時計回りに、左側がタップされている場合は反時計回りに回転するようUIViewをアニメーションしたいと思います。回転する私のコードは次のとおりです。反時計回りにアニメートする方法
func rotateRight() {
UIView.animate(withDuration: 0.5, animations: {
self.profileImageView.transform = CGAffineTransform(rotationAngle: (180.0 * CGFloat(M_PI))/180.0)
self.profileImageView.transform = CGAffineTransform(rotationAngle: (0.0 * CGFloat(M_PI))/360.0)
})
そして私は、セグメントがタップされたかに応じて変更を処理するために、このコードを使用しています(更新のために編集):
if loginRegisterSegmentedControl.selectedSegmentIndex == 0 {
self.loginRegisterButton.backgroundColor = UIColor.blue
loginRegisterSegmentedControl.tintColor = UIColor.blue
rotateLeft()
// Roll to the left
} else {
self.loginRegisterButton.backgroundColor = UIColor.red
loginRegisterSegmentedControl.tintColor = UIColor.red
rotateRight()
// Roll to the right
}
をだから、基本的にあれば、条件付きで私はrotateLeft()
機能に電話したいと思います - どうすればいいですか?
編集:ここではピアースの提案など、アニメーションのための私の完全なコード、です:
// Rotation
var viewAngle: CGFloat = 0 // Right-side up to start
let π = CGFloat.pi // Swift allows special characters hold alt+p to use this, it allows for cleaner code
func rotate(by angle: CGFloat) {
self.viewAngle += angle
UIView.animate(withDuration: 0.5, animations: {
self.profileImageView.transform = CGAffineTransform(rotationAngle: self.viewAngle)
self.view.layoutIfNeeded()
})
}
lazy var profileImageView: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(named: "TTTdude")
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFill
imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(rotate)))
imageView.isUserInteractionEnabled = true
return imageView
}()
lazy var loginRegisterSegmentedControl: UISegmentedControl = {
let sc = UISegmentedControl(items: ["iOS", "Android"])
sc.translatesAutoresizingMaskIntoConstraints = false
sc.tintColor = UIColor.black
sc.selectedSegmentIndex = 0
sc.addTarget(self, action: #selector(handleLoginRegisterChange), for: .valueChanged)
return sc
}()
func handleLoginRegisterChange() {
let title = loginRegisterSegmentedControl.titleForSegment(at: loginRegisterSegmentedControl.selectedSegmentIndex)
loginRegisterButton.setTitle(title, for: .normal)
if loginRegisterSegmentedControl.selectedSegmentIndex == 0 {
self.loginRegisterButton.backgroundColor = UIColor.blue
loginRegisterSegmentedControl.tintColor = UIColor.blue
rotate(by: -2*π)
// Roll to the left
} else {
self.loginRegisterButton.backgroundColor = UIColor.red
loginRegisterSegmentedControl.tintColor = UIColor.red
rotate(by: 2*π)
// Roll to the right
}
ちょうど好奇心から - なぜあなたは180 *π/ 180を使用しますか?それはちょうどπ – Pierce
ありがとう、それは素敵でシンプルでした - しかし、私は条件付き( 'if'は 'rotateLeft()'と 'else'''が' rotateRight() 'を持っています)を置き換えましたが、アニメーションに変更はありません左または右のセグメントをタップすると、常に時計回りに回転します。 – KingTim
ちょうど 'view.transform = CGAffineTransform(rotationAngle:-π)'と答えてください。 – Pierce