The final screen in our app is CheckoutView
, and it’s really a tale of two halves: the first half is the basic user interface, which should provide little real challenge for you; but the second half is all new: we need to encode our Order
class to JSON, send it over the internet, and get a response.
We’re going to look at the whole encoding and transferring chunk of work soon enough, but first let’s tackle the easy part: giving CheckoutView
a user interface. More specifically, we’re going to create a ScrollView
with an image, the total price of their order, and a Place Order button to kick off the networking.
For the image, I’ve provided two images in the files for this project, available from https://github.com/twostraws/HackingWithSwift. Look in the SwiftUI/project10-files folder, and copy both cupcakes@2x.jpg and cupcakes@3x.jpg into your asset catalog. We’ll need to use GeometryReader
to size this picture to the correct width of the screen, to avoid it stretching layouts on smaller devices.
As for the order cost, we don’t actually have any pricing for our cupcakes in our data, so we can just invent one – it’s not like we’re actually going to be charging people here. The pricing we’re going to use is as follows:
We can wrap all that logic up in a new computed property for Order
, like this:
var cost: Double {
// $2 per cake
var cost = Double(quantity) * 2
// complicated cakes cost more
cost += (Double(type) / 2)
// $1/cake for extra frosting
if extraFrosting {
cost += Double(quantity)
}
// $0.50/cake for sprinkles
if addSprinkles {
cost += Double(quantity) / 2
}
return cost
}
The actual view itself is straightforward: we’ll use a GeometryReader
to make sure our cupcake image is sized correctly, a VStack
inside a vertical ScrollView
, then our image, the cost text, and button to place the order.
We’ll be filling in the button’s action in a minute, but first let’s get the basic layout done – replace the existing body
of CheckoutView
with this:
GeometryReader { geo in
ScrollView {
VStack {
Image("cupcakes")
.resizable()
.scaledToFit()
.frame(width: geo.size.width)
Text("Your total is $\(self.order.cost, specifier: "%.2f")")
.font(.title)
Button("Place Order") {
// place the order
}
.padding()
}
}
}
.navigationBarTitle("Check out", displayMode: .inline)
That should all be old news for you by now. But the tricky part comes next…
SPONSORED Would you describe yourself as knowledgeable, but struggling when you have to come up with your own code? Fernando Olivares has a new book containing iOS rules you can immediately apply to your coding habits to see dramatic improvements, while also teaching applied programming fundamentals seen in refactored code from published apps.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.