Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Swift calculator

Hello,

I have 2 questions about the calculator I'm building in swift:

  1. I don't know how to program the , button and the π button
  2. I can't figure out which constraints to add to all the buttons...

The Xcode files are in GitHub: https://github.com/LucasPeters/Question-swift-calculator

Thank you

Jeff McDivitt
Jeff McDivitt
23,970 Points

Your are missing the assets folder in your project; therefore, nothing can be viewed and we cannot assist you. Please upload the complete project

2 Answers

I'm sorry about that... I uploaded the right files: https://github.com/LucasPeters/Question-swift-calculator/tree/master

Caleb Kleveter
MOD
Caleb Kleveter
Treehouse Moderator 37,862 Points

First, I really like your code. It could use some cleaning, but as far as how you are handling types and calculations, I really like it.

To handle the input for Pi, the number types (Int, Float, Double, etc) have a static property for each call pi, so your handler for that button press would look something like this:

@IBAction func btnPiPressed(_ sender: UIButton) {
    handleInput("\(Double.pi)")        
}

Th decimal press handler will do about the same thing, all you do is use '.' as the string:

@IBAction func btnDecimalPress(_ sender: UIButton) {
    handleInput(".")        
}

As far as the buttons go, using an image as the background is an interesting idea, but that will be a complete pain when trying to align things with it. The better way to do it is to color all the buttons background and adding constraints. This is a bit involved so I will link to a GitHub repo that you can look at the Storyboard:

https://github.com/calebkleveter/Calculator-Example

If what I did doesn't make sense, don't worry, you'll learn about auto-layout in this course.