NSTimer Class & Object Transformations (Xcode)NSTimer is a class used to execute code repeatedly or after a time interval. It is commonly used for:
👉 Simple idea: It runs code after every fixed interval (e.g., every 1 second).
Object transformation means changing a UI element’s:
👉 It is done using CGAffineTransform and animations.
Smooth visual change of UI elements over time.
Animations controlled using NSTimer for repeated updates.
Used to apply visual changes:
view.transform
var timer: Timer?
timer = Timer.scheduledTimer(timeInterval: 1.0,
target: self,
selector: #selector(updateUI),
userInfo: nil,
repeats: true)
@objc func updateUI() {
print("Timer fired!")
}
timer?.invalidate()
timer = nil
var xPosition: CGFloat = 0
@objc func moveView() {
xPosition += 10
animatedView.frame.origin.x = xPosition
}
timer = Timer.scheduledTimer(timeInterval: 0.1,
target: self,
selector: #selector(moveView),
userInfo: nil,
repeats: true)
view.transform = CGAffineTransform(translationX: 50, y: 0)
view.transform = CGAffineTransform(scaleX: 1.5, y: 1.5)
view.transform = CGAffineTransform(rotationAngle: .pi / 4)
👉 (π/4 = 45 degrees)
view.transform = CGAffineTransform.identity
UIView.animate(withDuration: 1.0) {
self.myView.transform = CGAffineTransform(scaleX: 2.0, y: 2.0)
}
myView.transform =
CGAffineTransform(translationX: 50, y: 50)
.rotated(by: .pi / 4)
.scaledBy(x: 1.5, y: 1.5)
Timer → triggers function repeatedly
↓
Update UI (position/transform)
↓
Animation effect on screen
UIView.animate for smooth animations@objc in selector methodsUIView.animate for UI animationsviewWillDisappearNSTimer runs code repeatedly after time intervals
Used for animations and repeated tasks
Object transformation includes:
UIView.animate provides smooth animations
Always invalidate timer when not needed
Used in games, sliders, and motion effects
Open this section to load past papers