2.2 KiB
2.2 KiB
Creating Views
This is a beginner tutorial. We will create a simple “Hello, world!" app using Adwaita.
Create the Swift Package
- Open your terminal client and navigate to a directory you want to create the package in (e.g.
~/Documents/). - Create a new folder for the package using
mkdir HelloWorld. - Enter the newly created folder using
cd HelloWorld. - Run
swift package init —type executablefor creating a new Swift package. - Open the Swift package. If you are using GNOME Builder, click on
Select a Folder…in the view that appears after opening Builder and open theHelloWorldfolder.
Add the Dependency
- Open the
Package.swiftfile. - Add the following line of code after
name: “HelloWorld”,:
dependencies: [.package(url: “https://github.com/david-swift/Adwaita”, from: “0.1.0”)],
Create the App
- Navigate to
Sources/main.swift. - An app that uses the Adwaita framework has a structure that conforms to the
Appprotocol. Thesceneproperty returns one or more windows which provide content for display. An@mainattribute marks it as the entry point of the app. Replaceprint(“Hello, world!”)by your first app. We will later defineHelloWindow:
@main
struct HelloWorld: App {
let id = "io.github.david-swift.HelloWorld"
var app: GTUIApp!
var scene: Scene {
HelloWindow()
}
}
Create a View
- Now, we will define
HelloWindow.HelloWindowis a view, that means it conforms to theViewprotocol. As it additionally is a window, we’ll make it conform to theWindowScenewhich automatically adds conformance toView.
struct HelloWindow: WindowScene {
var view: Body {
Text(“Hello, world!")
.padding()
}
}
- Run the executable Swift package (in GNOME Builder, press the play button, on the command line, use
swift run). You can see that one important component of a window in GNOME is missing: The header bar. - If you add another view inside of the
viewproperty ofHelloWindow, the views get aligned vertically:
struct HelloWindow: WindowScene {
var view: Body {
HeaderBar.empty()
Text(“Hello, world!")
.padding()
}
}