Skip to content

Hello World

S4cha edited this page May 8, 2017 · 4 revisions

Your first Component

Create a new file HelloWorldVC.swift

import Komponents

class HelloWorldVC: UIViewController, StatelessComponent {
    
    override func loadView() {
        loadComponent()
    }
    
    func render() -> Node {
        return
            View(style: { $0.backgroundColor = .white }, [
                Label("Hello World", style: { $0.centerInContainer() })
            ])
    }
}

Let's explain what's happening here.

First we want to add import Komponents at the top of our file. This is required to access Components features.

Here we create a UIViewController, so that we can present it on screen, this is classic iOS code. Then we say this is a StatelessComponent, which is pretty self-explanatory. Our component will render but has no state.

Calling loadComponent() inside loadView() will mount our component inside the UIViewController's view.

Finally, in the render method, we describe what we want to see on screen. Here we want a white view. This white view contains a Label "Hello World" which should be centered on both axis.

In your AppDelegate.swift

Show it on Screen

Let's show our first component on screen by linking it from the AppDelegate.

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
        window?.rootViewController = HelloWorldVC()
        
        // If you don's have any Storyboards you'll have to setup the window as well
        // window = UIWindow(frame: UIScreen.main.bounds)
        // window?.rootViewController = HelloWorldVC()
        // window?.makeKeyAndVisible()

        return true
    }
}

Congratulations! You just presented your first component on screen 🎉!

Clone this wiki locally