In this part we’ll see how use the Button in both the languages.
In QML we define the button in this way:
Button { text: "A button" id: control onClicked: { // Your action }}
Where in the “text” property we set the label of the button and in the onClicked is executed what we need when the button is tapped/clicked. Instead in SwiftUI we have:
Button(action: { // Your action }){ Text("button") }
For the SwiftUI button the code to execute when the user clicks the button go in the action block. Instead for the property about the text can be changed modifying the properties of the object Text. A example to customization the button with QML:
Button { text: "A button" id: control onClicked: { } contentItem: Text { text: control.text font: control.font opacity: enabled ? 1.0 : 0.3 color: control.down ? "#17a81a" : "#21be2b" horizontalAlignment: Text.AlignHCenter verticalAlignment: Text.AlignVCenter elide: Text.ElideRight } background: Rectangle { implicitWidth: 100 implicitHeight: 25 border.width: control.activeFocus ? 2 : 1 border.color: "#888" radius: 40 gradient: Gradient { orientation: Gradient.Horizontal GradientStop { position: 0 ; color: control.pressed ? "red" : "red" } GradientStop { position: 1 ; color: control.pressed ? "blue" : "blue" } } } }
To change the properties of the text we must assign an Text Object to the contenrItem (in this case QML and SwiftUI are similar) and to change the bacground we can assign a rectangle with solid color or with gradient. It’s possible also use other object (i.e. image) for the background. A example to customization the button with SwiftUI:
Button(action: {}) { Text("Button") .fontWeight(.bold) .font(.title) .padding() //.background(Color.red) .background(LinearGradient(gradient: Gradient(colors: [Color.red, Color.blue]), startPoint: .leading, endPoint: .trailing)) .cornerRadius(40) .foregroundColor(.white) .padding(10) }
In SwiftUI we change the background color (solid or not) modifying only the properties of the Text object because the Text object is used to “show” the button. If we want use an image for the button we must replace the Text object with the Image object.