adwaita.docc/Advanced/CreatingWidgets.md

63 lines
1.6 KiB
Markdown

# Creating widgets
Widgets are special views that do not provide a collection of other views as a content,
but have functions that are called when creating or updating the view.
Normally, a widget manages a GTK or Libadwaita widget using the C API.
## Recreate the Text widget
In this tutorial, we will recreate the ``Text`` widget.
A widget conforms to the ``Widget`` protocol:
```swift
struct CustomText: Widget { }
```
You can add properties to the widget:
```swift
struct CustomText: Widget {
var text: String
}
```
This widget can be called in a view body using `CustomText(text: "Hello, world!")`.
Now, add the function required by the protocol:
```swift
import CAdw
struct CustomText: Widget {
var text: String
func initializeWidget() -> Any {
gtk_label_new(text)?.opaque()
}
}
```
## Updates
The widget will be rendered as expected, but updates do not work currently.
To mark properties as a widget property, use the ``Property`` property wrapper.
```swift
import CAdw
struct CustomText: Widget {
@Property(
set: { gtk_label_set_label($0, text) },
pointer: OpaquePointer.self
)
var text: String
func initializeWidget() -> Any {
gtk_label_new(text)?.opaque()
}
}
```
## More Complex Widgets
If a property should allow two-way traffic (able to modify inside of the widget, e.g. the `isOn` property of a checkbox which can be updated when the user clicks the checkbox), use ``BindingProperty``. For views, use ``ViewProperty``.
More help is available [here](https://meta.aparoksha.dev/documentation/meta/createbackend).