Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Scroll text animation in Swift
import UIKit
import PlaygroundSupport
class MyViewController : UIViewController {
var label:UILabel!
var label2:UILabel!
let gap:CGFloat = 50
let rep:Float = Float.infinity
let shape:CAShapeLayer = {
return CAShapeLayer()
}()
var state:Int = 0
override func viewDidLoad() {
self.view.backgroundColor = .white
shape.frame = CGRect(x: 0, y: 0, width: 200, height: 50)
shape.backgroundColor = UIColor.blue.cgColor
shape.position = CGPoint(x:view.frame.width / 2, y:view.frame.height / 2)
shape.masksToBounds = true
label = trainingItemTitleLabel(width:200, color:.green)
label.center = self.view.center
label.text = "Hello"
label.center = CGPoint(x:shape.frame.width / 2, y:shape.frame.height / 2)
label2 = trainingItemTitleLabel(width:200, color:.red)
label2.center = self.view.center
label2.text = "Hello"
label2.center = CGPoint(x:shape.frame.width / 2, y:shape.frame.height / 2 - gap)
shape.addSublayer(label.layer)
shape.addSublayer(label2.layer)
let tmp = view.layer
tmp.addSublayer(shape)
view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap)))
}
@objc func handleTap() {
let animationPos = CABasicAnimation(keyPath: "position.y")
animationPos.fromValue = label.layer.position.y
animationPos.toValue = label.layer.position.y + gap
animationPos.duration = 0.5
animeKeep(anim:animationPos)
let animationPos2 = CABasicAnimation(keyPath: "position.y")
animationPos2.fromValue = label2.layer.position.y
animationPos2.toValue = label2.layer.position.y + gap
animationPos2.duration = 0.5
animeKeep(anim:animationPos2)
let mylayer = label.layer
let mylayer2 = label2.layer
if state == 0 {
mylayer.add(animationPos, forKey: "animationPos")
mylayer2.add(animationPos2, forKey: "animationPos2")
} else {
mylayer.add(animationPos2, forKey: "animationPos2")
mylayer2.add(animationPos, forKey: "animationPos")
}
state = 1 - state
}
func animeKeep (anim:CABasicAnimation) {
anim.fillMode = CAMediaTimingFillMode.forwards
anim.isRemovedOnCompletion = false
}
func trainingItemTitleLabel(width:CGFloat, color: UIColor) -> UILabel {
let label = UILabel()
label.text = ""
label.textAlignment = .center
label.backgroundColor = .clear
label.textColor = color
label.font = UIFont.boldSystemFont(ofSize: 50)
label.frame = CGRect(x: 0, y: 0, width: width, height: 50)
// label.center = center
return label
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
@greymd

This comment has been minimized.

Copy link
Owner Author

@greymd greymd commented Jan 21, 2020

movie

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment