Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Maegan Wilson
Maegan Wilson

Posted on • Edited on • Originally published atappsbymw.com

     

How to Make a Button with SwiftUI

If you are trying to follow along, please know that SwiftUI requires XCode 11 and macOS 10.15, all of which is in developer beta right now.

This post will walk you through how to make a basic iOS app that counts how many times a button is tapped.

1. Create a new project

The first step is to launch XCode and create a new single page iOS application. When creating the iOS app, make sureUse SwiftUI is checked.

New project

2. Create a variable and make the app output that variable

Next, we need to create a@State variable so that it can dynamically change when a button is tapped. Inside the ContentView struct, add@State var totalClicked: Int = 0 and change the string insideText() to"\(totalClicked)").

Your struct should look like this now.

structContentView:View{@StatevartotalClicked:Int=0varbody:someView{Text("Hello World")}}
Enter fullscreen modeExit fullscreen mode

3. Embed theText() in a Verticle Stack

Now, we need to embed the text in a verticle stack to place the button below theText(). To do this Command + Click on the0 in the live preview and chooseEmbed in VStack.

Menu that appears in XCode 11 when Command + Click on an object

By embedding in a VStack, the struct now looks like this:

structContentView:View{@StatevartotalClicked:Int=0varbody:someView{VStack{// this was addedText("Hello World")}}}
Enter fullscreen modeExit fullscreen mode

4. Add a Button with an action

It's time to add a button. A way to do this is by first adding aText(). Add the following to your struct:

// more stuff aboveVStack{Text("\(totalClicked)")Text("Increment Total) // <- This is what to add}// more stuff below
Enter fullscreen modeExit fullscreen mode

Now, let's use the live preview to embed theText() in a button. Command + Click on Increment Total in Live Preview and selectEmbed in Button.

Menu that appears in XCode 11 when Command + Click on an object

We need to adjust the Button code that is now inContentView.swift. Adjust button to look like the following:

varbody:someView{VStack{Text("\(totalClicked)")Button(action:{self.totalClicked=self.totalClicked+1}){Text("Increment Total")}}}
Enter fullscreen modeExit fullscreen mode

Now, if you run the app it will work!

5. (OPTIONAL) Add some style to the app!

Currently, the button and the text have no space between each other and the size of the total is quite small. In SwiftUI, you can adjust this pretty easily.

First, let's adjust the font size of the total by adding.font(.title) after the Text call.

Text("\(totalClicked").font(.title)
Enter fullscreen modeExit fullscreen mode

Next, we will add some space between the button and the text. To do this, we need to addSpacer() between the text and the button.

Text("\(totalClicked)").font(.title)Spacer()Button(action:{self.totalClicked=self.totalClicked+1}){Text("Increment Total")}
Enter fullscreen modeExit fullscreen mode

The touch target on the button is a little small, so to make it bigger we will add padding to it.

Button(action:{self.totalClicked=self.totalClicked+1}){Text("Increment Total")}.padding(.all)
Enter fullscreen modeExit fullscreen mode

The.all is adding padding to all sides of the button instead of just to the top, bottom, left, or right.

Finally, let's add padding to the entireVstack so that the app will fill the screen of the device.

varbody:someView{Vstack{Text("\(totalClicked)").font(.title)Spacer()Button(action:{self.totalClicked=self.totalClicked+1}){Text("Increment Total")}.padding(.all)}.padding(.all,40)}
Enter fullscreen modeExit fullscreen mode

The.padding(.all, 40) will tell thisVStack to have a 40 point distance to it's closest members on the top, left, right, and bottom.

Here is the finished repo

GitHub logo maeganwilson / totalClicked_tut

A tutorial for using a button in SwiftUI

SwiftUI Button Tutorial

A tutorial for using a button in SwiftUI

Places to read the tutorial

Did you like it?

If you liked the tutorial and project, please consider being a sponsor of this project and others like it by clicking the sponser button at the top of the repo, or by going directly to myPatreon.


If you enjoyed this article and want more, please consider subscribing to myPatreon and checking out my other posts!

If you don't like having more subscriptions, consider buying me a coffee by clicking the image below!Buy Me A Coffee

Top comments(10)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
nunez_giovanni profile image
Giovanni Nunez
Software Engineer at  Apple Comments and Thoughts are my own.
  • Location
    Austin
  • Education
    Bachelor of Computer Science
  • Work
    Software Engineer at Apple
  • Joined

Do you know how to add, say a border color and / or background color?

I decided to give swiftUI a shot. I just began learning UIKit and AppKit earlier this week 😅 so I am still trying to soak in all the differences from all 3 frameworks.

CollapseExpand
 
maeganwilson_ profile image
Maegan Wilson
I am an independent iOS developer and Apple product enthusiast.
  • Location
    Austin, Tx
  • Education
    BA in Theatre & Dance from the University of Texas at Austin
  • Work
    Software Engineer at Homeward
  • Joined

Here is the code sample:

Button(action:{print("Button was tapped")}){Text("Tap")}.border(.blue,width:3.0,cornerRadius:10.0).padding(.all,5.0)
CollapseExpand
 
nightsquid7 profile image
Nightsquid7
  • Joined

Awesome thanks! For some reason the apple documentation for border was buried beneath a bunch of links and I missed it. Glad you posted though!

Thread Thread
 
maeganwilson_ profile image
Maegan Wilson
I am an independent iOS developer and Apple product enthusiast.
  • Location
    Austin, Tx
  • Education
    BA in Theatre & Dance from the University of Texas at Austin
  • Work
    Software Engineer at Homeward
  • Joined

I have a hard time with the Apple Documentation, so I like to share when I find something like that!

CollapseExpand
 
nunez_giovanni profile image
Giovanni Nunez
Software Engineer at  Apple Comments and Thoughts are my own.
  • Location
    Austin
  • Education
    Bachelor of Computer Science
  • Work
    Software Engineer at Apple
  • Joined

woohoo. thanks for the example :-)
I just realized you're also from Austin. Hello, and thanks, neighbor!

Thread Thread
 
maeganwilson_ profile image
Maegan Wilson
I am an independent iOS developer and Apple product enthusiast.
  • Location
    Austin, Tx
  • Education
    BA in Theatre & Dance from the University of Texas at Austin
  • Work
    Software Engineer at Homeward
  • Joined

You're welcome!

Ah that's cool! Howdy!!

CollapseExpand
 
maeganwilson_ profile image
Maegan Wilson
I am an independent iOS developer and Apple product enthusiast.
  • Location
    Austin, Tx
  • Education
    BA in Theatre & Dance from the University of Texas at Austin
  • Work
    Software Engineer at Homeward
  • Joined
• Edited on• Edited

Yes to the border and border color! I'll put a gist together at lunch and link it here. Unfortunately, I'm still playing around with the background color stuff. That's been a little trickier for me to figure out.

Oh fun! Since I don't do any of this for work, I just try to focus on the new stuff and have fun. Hopefully, an app I write will make money some day.

CollapseExpand
 
salcidogrijalva profile image
Salcido Grijalva
not found
  • Email
  • Location
    Sonora, Mexico
  • Education
    Instituto Tecnológico de Hermosillo
  • Work
    Developer at Rivka Development
  • Joined

This looks so much like Flutter 😯

CollapseExpand
 
nicowernli profile image
Nicolás Wernli
  • Location
    La Cala del Moral, Málaga, España
  • Work
    Senior Software Developer at Cecil
  • Joined

Yes, swiftui is exactly what flutter is but just for iOS. Also swift makes the code look slightly cleaner, but the idea is the same

CollapseExpand
 
maeganwilson_ profile image
Maegan Wilson
I am an independent iOS developer and Apple product enthusiast.
  • Location
    Austin, Tx
  • Education
    BA in Theatre & Dance from the University of Texas at Austin
  • Work
    Software Engineer at Homeward
  • Joined

It does look similar! I haven't used Flutter, but just browsing the docs they look pretty close.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I am an independent iOS developer and Apple product enthusiast.
  • Location
    Austin, Tx
  • Education
    BA in Theatre & Dance from the University of Texas at Austin
  • Work
    Software Engineer at Homeward
  • Joined

More fromMaegan Wilson

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp