<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rey on Medium]]></title>
        <description><![CDATA[Stories by Rey on Medium]]></description>
        <link>https://medium.com/@reyhanmuhammadl?source=rss-f30a5fa725ab------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*tDGM59d1q7-Wf8vAvyU2RA.png</url>
            <title>Stories by Rey on Medium</title>
            <link>https://medium.com/@reyhanmuhammadl?source=rss-f30a5fa725ab------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 08:53:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@reyhanmuhammadl/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Make Fruit Ninja for iOS Using Swift]]></title>
            <link>https://medium.com/@reyhanmuhammadl/make-fruit-ninja-for-ios-using-swift-bf04868ce1a4?source=rss-f30a5fa725ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf04868ce1a4</guid>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Rey]]></dc:creator>
            <pubDate>Mon, 04 Dec 2023 03:28:56 GMT</pubDate>
            <atom:updated>2023-12-05T09:42:58.503Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BBLnnehVH40cMu1bQpMWMA.png" /></figure><p>For those of you who likes to play mobile games in the early boom of smartphone era, you might be familiar with Fruit Ninja. The game, that is probably one of the most iconic mobile game that has ever come out, is actually something that you can code on your own!</p><p>Okay, where do we begin?. For the sake of simplicity, I have already provide a basic project on <a href="https://github.com/reyhanl/WatermelonNinja/tree/main">Github</a>, go ahead and clone it!.</p><blockquote>You can also create a new project by using Command + Shift + N, then select Game. You have to pick SpriteKit for the engine. But, do not forget to get the asset on the Github link above.</blockquote><blockquote>Change your <strong>GameViewController.swift</strong> code from .aspectFill to .aspectFit in viewDidLoad()<br>scene.scaleMode = .aspectFit</blockquote><h3><strong>Explore</strong></h3><p>let’s explore a little bit. If you have coded an app using UIKit before but never try SpriteKit, you might be a little bit unfamiliar to the project structure.</p><p>There are 4 main files, and this is what each does.</p><blockquote><strong><em>Main.storyboard</em></strong>: Just like in a normal project, this is used as the entry point of a new project.</blockquote><blockquote><strong><em>GameViewController.swift</em></strong>: This file is responsible of displaying the GameScene.swift. you can how they do it on the viewDidLoad().</blockquote><blockquote><strong><em>GameScene.sks</em></strong>: This is kinda like the equivalent of .xib or .storyboard in a normal swift project. Basically this is the GameScene.swift xib.</blockquote><blockquote><strong><em>GameScene.swift</em></strong>: This is where the magic happen, all the logic and gameplay is going to be coded in this file.</blockquote><p>So, the file that we are going to focus on today is the <strong><em>Gamescene.swift</em></strong> file.</p><p>In <strong><em>GameScene.swift</em></strong>, there are some function that is important for this project.</p><p>The first one is <em>didMove()</em>, this one is kinda the viewDidLoad() in a UIKit project. You can do initial setup for your code in this function.</p><p>There are also <em>touchDown()</em>, <em>touchMove()</em>, <em>touchEnded()</em>. Just like the name, <em>touchDown()</em> is the called when you begin to touch the scene, <em>touchMove()</em> is the one that is going to be called every time your finger move on the scene, and <em>touchEnded()</em> is going to be called when your finger is lifted.</p><h3>What is Node?</h3><p>In SKScene, we are going to be using something called SKNode to display an Image, Label, or other.</p><p>So, where do we begin? first of, let’s see how we can add an object to the scene. There are a lot of subclass of SKNode, but the one we are going to be using is SKSpriteNode, this one can be used to display an image.</p><p>add these code to the <em>didMove()</em>, and run the project.</p><p><strong><em>GameScene.swift</em></strong></p><pre>let node = SKSpriteNode(imageNamed: &quot;watermelon&quot;)<br>node.position = .zero<br>node.size = .init(width: 100, height: 100)<br>addChild(node)</pre><p>Now you can see a watermelon on the center of the scene! Great, but wait a minute, did not we set the position to be .zero? why is not it positioned on the upper left size of the screen?</p><p>Well, in SKScene, positioning and coordinate system is a little bit different. So, the (0,0) coordinate is located right in the center.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SrAG_hcf4SMbxLdM0iqJoA.png" /><figcaption>GameScene.sks</figcaption></figure><p>It will be quite a challenge adjusting our brain to this coordinate system after using UIKit for like ever.</p><h3>Physics</h3><p>In order to make the game a little bit more realistic, we need to make the watermelon to fall.</p><p>We can do that by adding <em>SKPhysicsBody</em> to the node.</p><p><strong><em>GameScene.didMove()</em></strong></p><pre>let node = SKSpriteNode(imageNamed: &quot;watermelon&quot;)<br>node.position = .zero<br>node.size = .init(width: 100, height: 100)<br><br>//you can mess around with the number to experience it yourself<br>let body = SKPhysicsBody()<br>body.affectedByGravity = true<br>body.angularDamping = 0.2<br>body.charge = 0.2<br>body.allowsRotation = true<br>body.mass = 0.2<br>body.angularVelocity = .random(in: -1...1)<br><br>node.body = body        <br>addChild(node)</pre><p>Ok, now we know how to add a Sprite, lets get going with the game. Run the project, you will find yourself missing the Watermelon everytime.</p><h3><strong>The Basic Idea</strong></h3><p>The basic idea of fruit ninja is that every second or some period of time, we are going to create some instances of fruit at the bottom of the screen and throw it up for the user to slice.</p><p>Let’s make a class to simplify things later, and also two functions called makeWatermelon() and makeBody() to make Fruit:</p><pre>//<br>//  GameScene.swift<br>//  Tap<br>//<br>//  Created by reyhan muhammad on 03/12/23.<br>//<br><br>import SpriteKit<br>import GameplayKit<br><br>class GameScene: SKScene {<br>  <br>  private var label : SKLabelNode?<br>  private var spinnyNode : SKShapeNode?<br>   <br>  var slicedFruits: [SKNode] = []<br>  <br>  lazy var width: CGFloat = {<br>      let width = self.frame.width<br>      return width<br>  }()<br>  lazy var height: CGFloat = {<br>      let height = self.frame.height<br>      return height<br>  }()<br>  lazy var nodeSize: CGFloat = {<br>      let width = self.frame.width<br>      return width / 3<br>  }()<br>  <br>  override func didMove(to view: SKView) {        <br>      let watermelon = makeWatermelon()<br>      addChild(watermelon)  <br>  }<br>  <br>  func makeWatermelon(at: CGPoint? = nil) -&gt; SKNode{<br><br>      let node = Fruit()<br>      node.size = .init(width: nodeSize, height: nodeSize)<br>      <br>      let body = makeBody()<br>      node.physicsBody = body<br>              <br>      node.position = at ?? .zero<br>      return node<br>  }<br>  <br>  func makeBody() -&gt; SKPhysicsBody{<br>      let body = SKPhysicsBody()<br>      body.affectedByGravity = true<br>      body.angularDamping = 0.2<br>      body.charge = 0.2<br>      body.allowsRotation = true<br>      body.mass = 0.2<br>      body.angularVelocity = .random(in: -1...1)<br>              <br>      return body<br>  }<br>}<br><br>class Fruit: SKSpriteNode{<br>    var isOnScreen = false<br>    <br>    override init(texture: SKTexture?, color: UIColor, size: CGSize) {<br>        super.init(texture: texture, color: color, size: size)<br>        self.texture = .init(imageNamed: &quot;watermelon&quot;)<br>    }<br>    <br>    required init?(coder aDecoder: NSCoder) {<br>        super.init(coder: aDecoder)<br>        self.texture = .init(imageNamed: &quot;watermelon&quot;)<br>    }<br>}<br></pre><p>Now, how do we create some fruit every now and then?</p><pre>override func didMove(to view: SKView) {<br>        <br>    let timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in<br>        let watermelon = makeWatermelon()<br>        addChild(watermelon)<br>    }<br>}</pre><p>Let’s make a few fruits at the same time</p><pre> override func didMove(to view: SKView) {<br>        <br>    let timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in<br>        self.generateFruit()<br>    }<br>}<br><br>func generateFruit(){<br>    for i in 0...Int.random(in: 0...2){<br>        let x = CGFloat.random(in: -width / 2...width / 2)<br>        let node = makeWatermelon(at: .init(x: x, y: -height / 2))<br>        addChild(node)<br>    }<br>}</pre><p>Oke, if you run the project, you will not see a single fruit to be made, the reason is because we are positioning it at the bottom of the screen.</p><p>Let’s throw some fruits around!</p><p><strong><em>GameScene.swift</em></strong></p><pre>func generateFruit(){<br>    for i in 0...Int.random(in: 0...3){<br>        let x = CGFloat.random(in: -width / 2...width / 2)<br>        let node = makeWatermelon(at: .init(x: x, y: -height / 2))<br>        addChild(node)<br>        animateFruit(node: node)<br>    }<br>}<br><br>func animateFruit(node: SKNode){<br>    guard let body = node.physicsBody else{return}<br>    let moveX = CGFloat.random(in: -width / 2...width / 2)<br>    body.velocity = .init(dx: moveX, dy: height + height / 2)<br>}</pre><p>In that function, we are giving the body of the Node a velocity to make it move in a direction that we want. After some trial, I found that to be the “perfect” <em>dy</em> and for the <em>dx</em> I randomized it to be the size of the screen.</p><p>You can definitely improve it by making sure the alghoritm makes no watermelon to get out of bounds.</p><h3>Let’s slice</h3><p>Oke, now how do we slice it? The first thing to do is to add a function called sliceFruit(node: SKNode)</p><p>It will be much easier to imagine how it works if you turn off the generateFruit and just use one static fruit centered on the screen. Let’s make that function.</p><p><strong><em>GameScene.swift</em></strong></p><pre>  <br> override func didMove(to view: SKView) {<br>      <br>      addDummyWatermelon()<br>//    let timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in<br>//       self.generateFruit()<br>//    }<br>  }<br><br>func addDummyWatermelon(){<br>    let node = Fruit()<br>    node.size = .init(width: nodeSize, height: nodeSize)<br>    node.position = .zero<br>    addChild(node)<br>}</pre><p>So, after doing that, we can start on working on the slicing mechanism. We are not going to make it complicated for the simple version of the game, what we want to do now is to detect if a player move a finger on the screen, which we can use touchMoved() function.</p><p>Here is how you sliced it.</p><p><strong>GameScene.swift</strong></p><pre>var slicedFruits: [SKNode] = [] <br>func sliceFruit(node: SKNode){<br>  guard !slicedFruits.contains(node) else{return}<br>  slicedFruits.append(node)<br>  node.removeFromParent()<br>}<br><br>func touchMoved(toPoint pos : CGPoint) {<br>    if nodes(at: pos).count &gt; 0{<br>        for node in nodes(at: pos){<br>            if node is Fruit{<br>                sliceFruit(node: node)<br>            }<br>        }<br>    }<br>}</pre><p>Now, when you swipe your finger across a watermelon, it is now gone!</p><p>It is good, but does not feel as satisfying, isn’t it? So, we can make a simple animation for it.</p><p>As you may have noticed if you explore the Assets folder earlier, there are 2 other assets we have not used, leftSlice and rightSlice. We can use that image to simulate slicing effect in Fruit Ninja.</p><p>When user slice a fruit, we can just put two new Nodes with the leftSlice and rightSlice as their texture.</p><p><strong><em>GameScene.swift</em></strong></p><pre>func sliceFruit(node: SKNode){<br>    guard !slicedFruits.contains(node) else{return}<br>    slicedFruits.append(node)<br>    <br>    animateSliceFruit(node: node)<br>    <br>    score += 1<br>    <br>    node.removeFromParent()<br>}<br><br>func animateSliceFruit(node: SKNode){<br>    let rotation = node.zRotation<br><br>    let leftSlice = SKSpriteNode(imageNamed: &quot;sliceLeft&quot;)<br>    leftSlice.size = .init(width: nodeSize, height: nodeSize)<br>    leftSlice.position = node.position<br>    leftSlice.zPosition = 0<br>    leftSlice.physicsBody = makeBody()<br>    leftSlice.physicsBody?.velocity.dx = -nodeSize / 2<br>    leftSlice.zRotation = rotation<br>    addChild(leftSlice)<br>    <br>    let rightSlice = SKSpriteNode(imageNamed: &quot;sliceRight&quot;)<br>    rightSlice.size = .init(width: nodeSize, height: nodeSize)<br>    rightSlice.position = node.position<br>    rightSlice.physicsBody = makeBody()<br>    rightSlice.zPosition = 1<br>    rightSlice.physicsBody?.velocity.dx = nodeSize / 2<br>    rightSlice.zRotation = rotation<br>    addChild(rightSlice)<br>    <br>}</pre><p>We are also going to give them velocity.dx to make them separate from each other, now if you run it, you will be able to see the fruit getting sliced!.</p><h3>Scoring system</h3><p>Unlike a relationship, we really should keep score in this app.</p><p><strong><em>GameScene.swift</em></strong></p><pre>private lazy var scoreLabel : SKLabelNode = {<br>    let label = SKLabelNode(text: &quot;0&quot;)<br>    let rangeToLeftBorder = SKRange(lowerLimit: 10.0, upperLimit: 150.0)<br>    let distanceConstraint = SKConstraint.distance(rangeToLeftBorder, to: label)<br>    label.constraints = [distanceConstraint]<br>    label.position = .init(x: -width / 2 + 100, y: height / 2 - 100)<br>    return label<br>}()<br><br>var score = 0{<br>    didSet{<br>        scoreLabel.text = &quot;\(score)&quot;<br>    }<br>}<br><br>override func didMove(to view: SKView) {<br>    startGame()<br>}<br><br>func startGame(){<br>    score = 0<br>    addChild(scoreLabel)<br>    let timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in<br>        self.generateFruit()<br>    }<br>}<br><br>func sliceFruit(node: SKNode){<br>    //insert below all the previous code<br>    score += 1<br>}</pre><p>Let’s also move the didMove content to a dedicated function called <em>startGame()</em>, so that we can call it later. We are also adding a label to display score using <em>SKLabelNode</em>, and as you can see, the scoring system is not hard at all, we are only adding a variable that we change and then give an observer using didSet to update the score to the label automatically.</p><p>Now, if you run the project, the score will increment by one every single time you get a fruit sliced!</p><p>The next step is to add Heart to make the game more challenging!</p><p>Let’s create a class named Heart.swift</p><p><strong><em>Heart.swift</em></strong></p><pre><br><br>class Heart: SKSpriteNode{<br>    var isEmpty: Bool = false{<br>        didSet{<br>            texture = isEmpty ? .init(imageNamed: &quot;heart&quot;):.init(imageNamed: &quot;heart.fill&quot;)<br>        }<br>    }<br>    <br>    override init(texture: SKTexture?, color: UIColor, size: CGSize) {<br>        super.init(texture: texture, color: color, size: size)<br>        setSize()<br>    }<br>    <br>    required init?(coder aDecoder: NSCoder) {<br>        super.init(coder: aDecoder)<br>        setSize()<br>    }<br>    <br>    func setSize(){<br>        if let image = UIImage(named: &quot;heart&quot;) {<br>            let tempWidth = (width / 12)<br>            let tempHeight = tempWidth / image.size.width * image.size.height<br>            let size = CGSize(width: tempWidth, height: tempHeight)<br>            node.size = size<br>        }<br>    }<br>}</pre><p><strong><em>GameScene.swift</em></strong></p><pre>lazy var firstHealth: Heart = {<br>   let node = Heart()<br>    node.isEmpty = false<br>    node.setSize(width: width / 12)<br>    return node<br>}()<br>lazy var secondHealth: Heart = {<br>   let node = Heart()<br>    node.isEmpty = false<br>    node.setSize(width: width / 12)<br>    return node<br>}()<br>lazy var thirdHealth: Heart = {<br>   let node = Heart()<br>    node.isEmpty = false<br>    node.setSize(width: width / 12)<br>    return node<br>}()<br>var health = 3{<br>    didSet{<br>        if health == 2{<br>            executeHealth(node: thirdHealth)<br>        }else if health == 1{<br>            executeHealth(node: secondHealth)<br>            executeHealth(node: secondHealth)<br>        }else{<br>            executeHealth(node: thirdHealth)<br>            executeHealth(node: secondHealth)<br>            executeHealth(node: firstHealth)<br>            gameOver()<br>        }<br>    }<br>}<br><br>var generateFruitTimer: Timer?<br><br>override func didMove(to view: SKView) {<br>    addHeartNodes()<br>}<br><br>func addHeartNodes(){<br>    let safeAreaY = (height / 2) - 100<br>    let padding: CGFloat = 10<br>    firstHealth.position = .init(x: width / 2 - firstHealth.size.width, y: safeAreaY)<br>    addChild(firstHealth)<br>    <br>    secondHealth.position = firstHealth.position<br>    secondHealth.position.x -= firstHealth.frame.size.width + padding<br>    addChild(secondHealth)<br><br>    thirdHealth.position = secondHealth.position<br>    thirdHealth.position.x -= secondHealth.frame.size.width + padding<br>    addChild(thirdHealth)<br>}<br><br>func executeHealth(node: SKNode){<br>    guard let node = node as? Heart, !node.isEmpty else{return}<br>    node.isEmpty = true<br>    let leftSlice = SKSpriteNode(imageNamed: &quot;heart.sliceLeft&quot;)<br>    leftSlice.size = node.frame.size<br>    leftSlice.position = node.position<br>    leftSlice.zPosition = 0<br>    leftSlice.physicsBody = makeBody()<br>    leftSlice.physicsBody?.velocity.dx = -nodeSize / 2<br>    addChild(leftSlice)<br>    <br>    let rightSlice = SKSpriteNode(imageNamed: &quot;heart.sliceRight&quot;)<br>    rightSlice.size = node.frame.size<br>    rightSlice.position = node.position<br>    rightSlice.physicsBody = makeBody()<br>    rightSlice.zPosition = 1<br>    rightSlice.physicsBody?.velocity.dx = nodeSize / 2<br>    addChild(rightSlice)<br>    <br>    node.isEmpty = true<br>}<br><br>func gameOver(){<br>    generateFruitTimer?.invalidate()<br>    for child in children.filter({$0 is Fruit}){<br>        animateSliceFruit(node: child)<br>    }<br>}</pre><p>We are creating a SKSpriteNode subclass called Heart that is responsible of displaying the Heart.png while also keeping track of whether or not they have been broken.</p><p>Now, I do not understand much about Constraint in GameScene, but hey that works 🤷🏼‍♂️. We are manually but not in a bad looking way positioning the Heart in the <strong>addHeartNodes()</strong>.</p><p>We are also going to be animating the heart when it is broken / player losing heart, because why not?. The implementation is pretty much the same with the <strong>animateSliceFruit()</strong>, By making a sliced heart into two pieces of node that is placed on top of the Heart that is broken, then give it a velocity in horizontal direction.</p><p>Now, Let’s add a way for us to detect if a watermelon is not sliced.</p><p><strong><em>GameScene.swift</em></strong></p><pre>//this function is called anytime any update happen, so basically every frame.<br>override func didSimulatePhysics() {<br>    super.didSimulatePhysics()<br>    //this is below the screen<br>    let bottom = -(height / 2)<br>    for node in children{<br>        if let node = node as? Fruit{<br>        //since we create the fruit below<br>        //the screen, we need to make sure it goes to the scene first before<br>        //we detect it to be a missed fruit.<br>            if node.position.y &gt; bottom{<br>                node.isOnScreen = true<br>            }else if node.isOnScreen &amp;&amp; node.position.y &lt; bottom{<br>                node.removeFromParent()<br>                guard health != 0 else{return}<br>                health -= 1<br>            }<br>        }else{<br>            //this is for all the sliced animation<br>            if node.position.y &lt; bottom{<br>                node.removeFromParent()<br>            }<br>        }<br>    }<br>}</pre><p>Yep, that did it! now if you missed another watermelon and wasted it, it will break a single heart :(.</p><p>The next thing is of course <strong>THE BOMB</strong>! 💣</p><p><strong><em>Bomb.swift</em></strong></p><pre>class Bomb: SKSpriteNode{<br>    override init(texture: SKTexture?, color: UIColor, size: CGSize) {<br>        super.init(texture: texture, color: color, size: size)<br>        self.texture = .init(imageNamed: &quot;bomb&quot;)<br>    }<br>    <br>    required init?(coder aDecoder: NSCoder) {<br>        super.init(coder: aDecoder)<br>        self.texture = .init(imageNamed: &quot;bomb&quot;)<br>    }<br>}</pre><p><strong><em>GameScene.swift</em></strong></p><pre>var isGameOver: Bool = false<br><br>func startGame(){<br>    score = 0<br>    health = 3<br>    isGameOver = false<br>    generateFruitTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in<br>        self.generateFruit()<br>    }<br>    addHeartNodes()<br>}<br>func touchMoved(toPoint pos : CGPoint) {<br>    if nodes(at: pos).count &gt; 0{<br>        for node in nodes(at: pos){<br>            if node is Fruit{<br>                sliceFruit(node: node)<br>            }else if node is Bomb{<br>                guard isGameOver == false else{return}<br>                isGameOver = true<br>                self.generateFruitTimer?.invalidate()<br>                node.run(.scale(by: 2, duration: 0.2)) {<br>                    node.run(.scale(by: 0.5, duration: 0.2)) { [weak self] in<br>                        self?.health = 0<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>In SKScene, the way we do animation or action is by using node.run(), there is all kind of thing that you can do, so be sure to check it out yourself!. Run the project, you will see that the bomb is a real threat!.</p><p>Now, let’s do final step, which is to display a retry button. We are going to be adding SKSpriteNode as Retry Button instead of creating a subclass because it is not really necessary to do that.</p><pre>lazy var retryButton: SKSpriteNode = {<br>   let node = SKSpriteNode()<br>    node.texture = .init(imageNamed: &quot;retry&quot;)<br>    node.size = .init(width: width / 5, height: width / 5)<br>    node.name = &quot;retry&quot;<br>    return node<br>}()<br>func addRetryButton(){<br>    addChild(retryButton)<br>}<br>func gameOver(){<br>    generateFruitTimer?.invalidate()<br>    for child in children.filter({$0 is Fruit}){<br>        animateSliceFruit(node: child)<br>    }<br>    addRetryButton()<br>}<br>func touchDown(atPoint pos : CGPoint) {<br>    for node in nodes(at: pos){<br>        if node.name == &quot;retry&quot;{<br>            retryButton.removeFromParent()<br>            startGame()<br>        }<br>    }<br>}</pre><p>Now, the game is completed! Of course, there are all kind of thing that you can do like setting up a dedicated screen before the game started. But, hey let’s wrap it up before we spend too much time in this game 🫣.</p><blockquote>Too lazy to read and code? I gotchu. Check out the code <a href="https://github.com/reyhanl/WatermelonNinja">here</a>.</blockquote><p>Hey guys, thank you for reading this post. If you have any other topic that you would love to get to know more, please do let me know in the comment section down below or dm me here.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf04868ce1a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Transition Using UIViewControllerTransitioningDelegate (Swift)]]></title>
            <link>https://blog.devgenius.io/custom-transition-using-uiviewcontrollertransitioningdelegate-swift-4b921d52f65a?source=rss-f30a5fa725ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b921d52f65a</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[uikit]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Rey]]></dc:creator>
            <pubDate>Tue, 28 Nov 2023 23:32:03 GMT</pubDate>
            <atom:updated>2023-12-04T16:28:47.139Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K6gN6Y-A7YBRCuYmqvsAkQ.png" /></figure><p>Have you ever wondered how Instagram and Spotify<br>make an Interactable Custom transition between UIViewController? Well, you are not alone!</p><p>It turns out, they are using UIViewControllerTransitioningDelegate, and here is how they did it!</p><h3>Let’s get started</h3><p>In order to save some time, let’s clone the <a href="https://github.com/reyhanl/CustomTransition/">base project</a> that I have uploaded to github.</p><blockquote>git clone <a href="https://github.com/reyhanl/CustomTransition.git">https://github.com/reyhanl/CustomTransition.git</a></blockquote><p>You can find the base project on the main branch. After you clone the project, we are good to go!</p><h3>Create a TransitioningManager</h3><p>So, how do we customize the transition? Well, UIViewController has a property called transitioningDelegate, what we need to do now is to have an object to conform to that protocol.</p><p>Let’s create one, let’s call it TransitioningManager.</p><pre>import UIKit<br><br>class TransitioningManager: NSObject, UIViewControllerTransitioningDelegate{<br>    <br>    weak var interactionController: UIPercentDrivenInteractiveTransition?<br>    var presentationTransitionType: CustomPresentationTransitionType?<br>    var dismissalTransitionType: CustomDismissTransitionType?<br>    <br>   func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -&gt; UIViewControllerAnimatedTransitioning? {<br>        return PresentationHandler(presentationTransitionType: presentationTransitionType)<br>    }<br>    <br>    func animationController(forDismissed dismissed: UIViewController) -&gt; UIViewControllerAnimatedTransitioning? {<br>        return DismissalHandler(dismissTransitionType: dismissalTransitionType)<br>    }<br>    <br>    func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -&gt; UIPresentationController? {<br>        return PresentationController(presentedViewController: presented, presenting: presenting)<br>    }<br>    <br>    func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -&gt; UIViewControllerInteractiveTransitioning? {<br>        return interactionController<br>    }<br>    <br>    func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -&gt; UIViewControllerInteractiveTransitioning? {<br>        return interactionController<br>    }<br>}</pre><p>Ok, let’s talk about what each of those function do and ask in return.</p><p><strong>1, 2</strong>: those two ask you to return UIViewControllerAnimatedTransitioning and this object that you return is going to be the place where we put all the animation stuff!</p><p><strong>3: </strong>asking for an object that conform to UIPresentationController, We are asked to return an object that conform to that protocol, in which it contains information like the size of the view controller that you want to present etc.</p><p><strong>4, 5:</strong> ask for UIViewControllerInteractiveTransitioning to handle the interactive transition.</p><p>For example, if you are planning to present a view controller using a pan gesture, you are going to be using <strong><em>UIViewControllerInteractiveTransitioning</em></strong> like <strong><em>UIViewControllerInteractiveTransitioning</em></strong> to tell the progress of the transition ranging from 0–1.</p><h4><strong>Create </strong>PresentationHandler &amp; DismissalHandler</h4><p>Let’s create a class that conform to each of previously mentioned protocol.</p><p>First, let’s separate the model for presentation and dismissal into two separate classes. You could actually put it into one, but the code would be a little bit too crowded with switch or if-else statement.</p><p>UIViewControllerAnimatedTransitioning has two main function.</p><p><em>transitionDuration() -&gt; TimeInterval, </em>this function determine the overall speed of the transition and</p><p><em>animateTransition(),</em> this is where we would be putting all the animation.</p><p>As for the CustomPresentationTransitionType &amp; CustomDismissTransitionType, we are going to be using it to differentiate between one type of animation with another.</p><pre>class PresentationHandler: NSObject, UIViewControllerAnimatedTransitioning{<br>    <br>    var presentationTransitionType: CustomTransitionType?<br>    <br>    init(presentationTransitionType: CustomTransitionType? = nil) {<br>        self.presentationTransitionType = presentationTransitionType<br>    }<br>    <br>    <br>    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -&gt; TimeInterval {<br>        return 0.5<br>    }<br>    <br>    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {<br>        //Here is where you animate stuff<br>    }<br>}<br><br>class DismissalHandler: NSObject, UIViewControllerAnimatedTransitioning{<br>    <br>    var dismissTransitionType: CustomDismissTransitionType?<br>    <br>    init(dismissTransitionType: CustomDismissTransitionType? = nil) {<br>        self.dismissTransitionType = dismissTransitionType<br>    }<br>    <br>    <br>    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -&gt; TimeInterval {<br>        return 0.5<br>    }<br>    <br>    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {<br>        //Here is where you animate stuff<br>    }<br>}<br><br><br>class PresentationController: UIPresentationController {<br>    <br>    var transitionType: CustomTransitionType?<br>    <br>    override var shouldRemovePresentersView: Bool {<br>        //If you return false, you would be limited when you are trying to modify the <br>        //FromViewController / presenting view controller<br>        return true<br>    }<br>}<br><br>enum CustomPresentationTransitionType{<br>    case swipeRight<br>}<br><br>enum CustomDismissTransitionType{<br>    case swipeLeft<br>}</pre><p>Now, add some code to the TransitioningManager class</p><pre>class TransitioningManager: NSObject, UIViewControllerTransitioningDelegate{<br>    <br>    weak var interactionController: UIPercentDrivenInteractiveTransition?<br>    var presentationTransitionType: CustomPresentationTransitionType?<br>    var dismissalTransitionType: CustomDismissTransitionType?<br>    <br>    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -&gt; UIViewControllerAnimatedTransitioning? {<br>        return PresentationHandler(presentationTransitionType: presentationTransitionType)<br>    }<br>    <br>    func animationController(forDismissed dismissed: UIViewController) -&gt; UIViewControllerAnimatedTransitioning? {<br>        return DismissalHandler(dismissTransitionType: dismissalTransitionType)<br>    }<br>    <br>    func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -&gt; UIPresentationController? {<br>        return PresentationController(presentedViewController: presented, presenting: presenting)<br>    }<br>    <br>    func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -&gt; UIViewControllerInteractiveTransitioning? {<br>        return interactionController<br>    }<br>    <br>    func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -&gt; UIViewControllerInteractiveTransitioning? {<br>        return interactionController<br>    }<br>}</pre><p>Neat! but it still won’t do anything. Do not worry, we are getting real close to the MVP.</p><p>Now, let’s edit the <em>PresentationHandler.</em></p><p><strong><em>PresentationHandler.swift</em></strong></p><pre>func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {<br>    switch presentationTransitionType {<br>    case .swipeRight:<br>        handleSwipeRight(using: transitionContext)<br>    case nil:<br>        break<br>    }<br>}<br><br>func handleSwipeRight(using transitionContext: UIViewControllerContextTransitioning){<br>    guard let fromView = transitionContext.view(forKey: .from),<br>          let toView = transitionContext.view(forKey: .to)<br>    else{return}<br>    let containerView = transitionContext.containerView<br>    <br>    containerView.addSubview(toView)<br>    //we are setting the initial position for the ToViewController.view, we are setting it to the left of the screen<br>    toView.frame = fromView.frame<br>    toView.frame.origin.x = -fromView.frame.width<br>    <br>    let duration = transitionDuration(using: transitionContext)<br>    UIView.animate(withDuration: duration) {<br>        //we are moving the toVC.view to the screen, and moving the fromView to the<br>        //end of the screen<br>        toView.frame.origin.x = 0<br>        fromView.frame.origin.x = fromView.frame.width<br>    } completion: { _ in<br>        if transitionContext.transitionWasCancelled{<br>            toView.frame.origin.x = -fromView.frame.width<br>            toView.removeFromSuperview()<br>            fromView.frame.origin.x = 0<br>        }else{<br>            fromView.removeFromSuperview()<br>        }<br>        transitionContext.completeTransition(!transitionContext.transitionWasCancelled)<br>    }<br>}</pre><p>First, we need to get the view of the presenting view controller, and the presented view controller. We then do some setup to position each view before we start the animation. You can pretty much execute any kind of UIView animation that you can think of, and it will be executed properly.</p><p>Now, let’s add the code below to the FromViewController to test our new fancy transition.</p><pre>class FromViewController: UIViewController {<br><br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        view.backgroundColor = .blue<br>    }<br>    <br>    override func viewDidAppear(_ animated: Bool) {<br>        super.viewDidAppear(animated)<br>        presentToVC()<br>    }<br><br>    func presentToVC(){<br>        let vc = ToViewController()<br>        <br>        let customTransition = TransitioningManager()<br>        customTransition.presentationTransitionType = .swipeLeft<br>        <br>        vc.modalPresentationStyle = .custom<br>        vc.transitioningDelegate = customTransition<br>        present(vc, animated: true)<br>    }<br><br>}</pre><p><strong>It works!</strong> but how do we make it interactive like Instagram when you are swiping right to open camera? well, you need <strong><em>UIViewControllerInteractiveTransitioning</em></strong>.</p><p>but before that, let’s create a protocol to make things simpler.</p><pre>protocol CustomTransitionEnabledVC{<br>    var interactionController: UIPercentDrivenInteractiveTransition? { get set }<br>    var customTransitionDelegate: TransitioningManager {get set}<br>}</pre><p>Apply that to ToViewController. Now, let’s make some adjustment to how we present ToViewController in the FromViewController.</p><pre>class ToViewController: UIViewController, CustomTransitionEnabledVC {<br>  <br>    var customTransitionDelegate = TransitioningManager()<br>    var interactionController: UIPercentDrivenInteractiveTransition?<br>}<br><br>class FromViewController: UIViewController, CustomTransitionEnabledVC {<br>    <br>    var customTransitionDelegate = TransitioningManager()<br>    var interactionController: UIPercentDrivenInteractiveTransition?<br>}</pre><p>Now, let’s add <strong><em>UIPanGestureRecognizer</em></strong> onto the stage.</p><pre><br>class FromViewController: UIViewController, CustomTransitionEnabledVC {<br>   <br>    var customTransitionDelegate = TransitioningManager()<br>    var interactionController: UIPercentDrivenInteractiveTransition?<br><br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        view.backgroundColor = .blue<br>        addPanGestureRecognizer()<br>    }<br>    <br>    override func viewDidAppear(_ animated: Bool) {<br>        super.viewDidAppear(animated)<br>        presentToVC()<br>    }<br>    <br>    func addPanGestureRecognizer(){<br>        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handleTransition(_:)))<br>        <br>        view.isUserInteractionEnabled = true<br>        view.addGestureRecognizer(panGesture)<br>    }<br><br>     func presentToVC(){<br>        let vc = ToViewController()<br>        <br>        interactionController = UIPercentDrivenInteractiveTransition()<br>        <br>        //we are setting the interaction controller and the presentation type<br>        //So that we can controll the transition status in the panGesture handler<br>        vc.customTransitionDelegate.interactionController = interactionController<br>        vc.customTransitionDelegate.presentationTransitionType = .swipeLeft<br><br>        vc.transitioningDelegate = vc.customTransitionDelegate<br>        vc.modalPresentationStyle = .custom<br>        present(vc, animated: true)<br>    }<br><br>    @objc func handleTransition(_ gestureRecognizer: UIPanGestureRecognizer){<br>        let translationX = gestureRecognizer.translation(in: view).x<br>        let percentageInDecimal = translationX / view.frame.width<br>        <br>        switch gestureRecognizer.state {<br>        case .began:<br>            presentToVC()<br>        case .changed:<br>            //it accepts value between 0 -&gt; 1<br>            interactionController.update(percentageInDecimal)<br>        case .ended:  <br>            //if user has swipe half the length of the Screen when <br>            // pan gesture ended, we should continue presenting the <br>            // ToViewController.<br>            if percentageInDecimal &gt; 0.5{<br>                interactionController.finish()<br>            }else{<br>                interactionController.cancel()<br>            }<br>        default:<br>            break<br>        }<br>    }<br>}</pre><p>If you run the project, you will find that it is working like a charm!</p><p>But wait, how do we do it in reverse..I mean it would be really lame if there is no way of swipe left to dismiss, right?</p><h3><strong>Applying Swipe Left To Dismiss</strong></h3><p>The next step is pretty much the same with the previous one, except that it is done in reverse. Since we have already set the <em>transitioningDelegate</em> of <strong><em>ToViewController</em></strong> to itself, all we need to do is to provide the <em>interactionController</em> and <em>dismissalTransitionType</em> to the customTransitionDelegate.</p><pre>class ToViewController: UIViewController, CustomTransitionEnabledVC {<br>    <br>    var interactionController: UIPercentDrivenInteractiveTransition?<br>    var customTransitionDelegate = TransitioningManager()<br><br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        view.backgroundColor = .red<br>        addPanGestureRecognizer()<br>        // Do any additional setup after loading the view.<br>    }<br><br>    func addPanGestureRecognizer(){<br>        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handleTransition(_:)))<br>        <br>        view.isUserInteractionEnabled = true<br>        view.addGestureRecognizer(panGesture)<br>    }<br>    <br>    @objc func handleTransition(_ gestureRecognizer: UIPanGestureRecognizer){<br>        let translationX = gestureRecognizer.translation(in: view).x<br>        let percentageInDecimal = -translationX / view.frame.width<br>        <br>        switch gestureRecognizer.state {<br>        case .began:<br>            interactionController = UIPercentDrivenInteractiveTransition()<br>            customTransitionDelegate.interactionController = interactionController<br>            customTransitionDelegate.dismissalTransitionType = .swipeLeft<br>            dismiss(animated: true)<br>        case .changed:<br>            print(percentageInDecimal)<br>            interactionController?.update(percentageInDecimal)<br>        case .ended:<br>            if percentageInDecimal &gt; 0.5{<br>                interactionController?.finish()<br>            }else{<br>                interactionController?.cancel()<br>            }<br>        default:<br>            break<br>        }<br>    }<br>}</pre><pre><br>class DismissalHandler: NSObject, UIViewControllerAnimatedTransitioning{<br>    <br>    var dismissTransitionType: CustomDismissTransitionType?<br>    <br>    init(dismissTransitionType: CustomDismissTransitionType? = nil) {<br>        self.dismissTransitionType = dismissTransitionType<br>    }<br>    <br>    <br>    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -&gt; TimeInterval {<br>        return 0.5<br>    }<br>    <br>    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {<br>        switch dismissTransitionType {<br>        case .swipeLeft:<br>            handleSwipeLeft(using: transitionContext)<br>        case nil:<br>            break<br>        }<br>    }<br>    <br>    func handleSwipeLeft(using transitionContext: UIViewControllerContextTransitioning){<br>        guard let fromView = transitionContext.view(forKey: .from),<br>              let toView = transitionContext.view(forKey: .to)<br>        else{return}<br>        let containerView = transitionContext.containerView<br>        <br>        containerView.addSubview(toView)<br>        //we are setting the initial position for the ToViewController.view, we are setting it to the left of the screen<br>        toView.frame = fromView.frame<br>        toView.frame.origin.x = fromView.frame.width<br>        <br>        let duration = transitionDuration(using: transitionContext)<br>        UIView.animate(withDuration: duration) {<br>            toView.frame.origin.x = 0<br>            fromView.frame.origin.x = -fromView.frame.width<br>        } completion: { _ in<br>            if transitionContext.transitionWasCancelled{<br>                toView.frame.origin.x = -fromView.frame.width<br>                toView.removeFromSuperview()<br>                fromView.frame.origin.x = 0<br>            }else{<br>                fromView.removeFromSuperview()<br>            }<br>            transitionContext.completeTransition(!transitionContext.transitionWasCancelled)<br>        }<br>    }<br>}</pre><p>It’s a wrapped! if you are running the project, you’ll find that now you can swipe left and right to go back and forth between ViewController!</p><p>What do you think of this feature? would you like to see how it is done in SwiftUI? stay tuned!.</p><p>Thanks for the time, I wish you a great journey ahead in your iOS Development roadmap.</p><blockquote>If you do not have time to implement and code all these, do not worry! I gotchu 😉, you can head out to and download the project <a href="https://github.com/reyhanl/CustomTransition/tree/finish">here</a> on the <strong>finish</strong> branch.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b921d52f65a" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/custom-transition-using-uiviewcontrollertransitioningdelegate-swift-4b921d52f65a">Custom Transition Using UIViewControllerTransitioningDelegate (Swift)</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make your GitHub profile more Interesting]]></title>
            <link>https://medium.com/@reyhanmuhammadl/make-your-github-profile-more-interesting-fe08f3de82fb?source=rss-f30a5fa725ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe08f3de82fb</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Rey]]></dc:creator>
            <pubDate>Wed, 21 Sep 2022 01:24:21 GMT</pubDate>
            <atom:updated>2022-09-21T01:24:21.832Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kU2uzuU51plcvrem4IzAyg.png" /></figure><p>I have used GitHub for like a long time at this point, but my profile had always been like not good for the past couple of years until I discovered some of these things.</p><h4>Add ReadMe file to your profile</h4><p>Apparently, you can add a ReadMe file to not just your project but also your profile.</p><p>So the way to do it is basically by creating a Repository with your username, after that, all you need to do is add ReadMe file to that repository. By using this ReadMe, you can use <a href="https://www.markdownguide.org/">MarkDown</a> to display an image or even to show some bullet point to make yourself stand out from other people profile.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lsOcLTg0A_aIpKwMF_L4sQ.png" /></figure><p>This might not be the best example there is but at least it shows you how much more color you can add to your profile, so, what are you waiting for? go ahead and try it.</p><h4>Your Contribution Is Not Looking Good?</h4><p>Have you ever look at your contribution and realize that it looks really pale and empty? well, I am no different. The problem is that, some of us is only contributing to our own repository that is private to us, therefore, the Contribution Chart is going to look a little empty compared to people who contribute to open source project.</p><p>But, you can actually enable a setting to include all your private contribution anonymously. All you need to do is to head over to your profile</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L8mtOXqolobftkyBges7ow.png" /></figure><p>then, click on Contribution settings, and turn on Private contribution.</p><h4>Conclusion</h4><p>GitHub have given us the option to make our profile more stand out than the rest. It is our duty to use all the feature that is enabled by GitHub to optimize our chances in getting in for that opportunity that we have always wanted.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe08f3de82fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>