UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

That page doesn't exist, but based on searching the site here are some pages that might be what you're looking for…

How to lock a view controller’s orientation using supportedInterfaceOrientations

Example Code At the project level you can configure which orientations your whole app should support, but sometimes you want individual view controllers to support a subset of those. For example, you might want most of your app to work in any orientation, but one part to work specifically in portrait. To configure this, you need to override the supportedInterfaceOrientations property ... Read more >>

How to read the interface orientation: portrait or landscape?

Example Code Apple generally doesn’t want developers to think about things like “portrait” and “landscape” because devices come in a range of sizes, and in the case of iPad you get slide over and split view on top. However, sometimes it’s just... Read more >>

How to lock Interface Builder controls to stop accidental changes

Example Code Interface Builder is the standard tool for making iOS interfaces using drag and drop, but it does make it remarkably easy to make a mistake – moving a view by accident, adjusting a property with a typo, or perhaps embedding one vie... Read more >>

Posting notifications to the lock screen

Project For the final part of our app, we’re going to add another button to our list swipe actions, letting users opt to be reminded to contact a particular person. This will use iOS’s UserNotifications framework to create a local notification, and ... Read more >>

UIStackView by example

Project ...Auto Layout-powered view container that makes it even easier to build complex user interfaces. As an example, lets say you want users to fill in a short form: you have a label saying "Name" then a UITextField to the right of it; beneath that you have another label saying "Address" and a UITextView be... Read more >>

UIActivityViewController by example

Article ...o add our app’s own services alongside the others. In this article I'll walk through some complete examples of using UIActivityViewController, partly so you can see what it’s capable of, and partly also so you have one reference guide to refer back to in the future. Sharing basic content Let’s ... Read more >>

NSAttributedString by example

Article ...UITextView, both of which accept attributed strings directly. In this article I'll walk you through examples of what NSAttributedString is capable of: creating strings by hand, adding and enumerating attributes, adding links and images, and more. All these code samples are written to work with a Swi... Read more >>

How to find the view controller responsible for a view

Example Code If you need to find the view controller that is responsible for a particular view, the easiest thing to do is walk the responder chain. This chain is built into all iOS apps, and lets you walk from one view up to... Read more >>

SwiftUI by Example: Now updated for iOS 16

Article This week I published the biggest ever update to SwiftUI by Example, adding lots of new sample code plus 100 new Xcode projects to download. The initial goal was to update the book for iOS 16, but I ended up going back and adding coverage of functionality intr... Read more >>

Learn SwiftUI with SwiftUI By Example

Article Many people are keen to learn SwiftUI in the fastest way possible, which is why I wrote SwiftUI By Example: a comprehensive, free collection of example code that helps you get started with SwiftUI today. Not only does SwiftUI By Example walk you through well over 100 common coding problems and solu... Read more >>

How to render example content using prepareForInterfaceBuilder()

Example Code Whenever you create a custom UIView subclass using @IBDesignable, it’s usually a good idea to provide it with some sample content so it can render meaningfully at design time. For example, here’s a simple ShapeView class that renders a UIBezierPath inside a view, using CAShapeLayer: @IBDesignable class ShapeView: UIView { @IBInspectable var strokeColor: UIColor = UIColor.... Read more >>

How to use view controller containment

Example Code View controller containment allows you to embed one view controller inside another, which can simplify and organize your code. It takes four steps: Call addChild() on your parent view controller, passing in your child. Set the child’s f... Read more >>

How do you show a modal view controller when a UITabBarController tab is tapped?

Example Code Usually tapping a tab in a UITabBar shows that tab, but it's often the case that you want to override that behavior, for example to show a view modally. If you're using one of Xcode's built-in storyboard templates for creating your user interface, it's not immediately obvious how to do this, but fortunately it's not so ... Read more >>

How to fix the error “View controller is unreachable because it has no entry points and no identifier for runtime access”

Example Code ...a segue from an existing view controller. This might be a button click or a table cell selection for example. To do that, select the component that should trigger the segue, then Ctrl-drag from there to the disconnected view controller. Once all view controllers have a way of accessing them the warning should disappear. Read more >>

How to hide the tab bar when a view controller is shown

Example Code If you’re using UITabBarController to display a tab strip at the bottom of your user interface, the default behavior for iOS is to display the tabs at all times – even if the user has navigated deep into a UINavigationController in ... Read more >>

How to fix the error “Failed to instantiate the default view controller for UIMainStoryboardFile”

Example Code This error happens due to a simple mistake in your storyboard, and it’s easy to fix. When your app starts, iOS needs to know precisely which view controller needs to be shown first – known as your default view controll... Read more >>

How to customize a view controller’s back button on a navigation bar: backBarButtonItem

Example Code ...ters of your button, because even with a custom title it’s still just a back button. Here’s some example code: navigationItem.backBarButtonItem = UIBarButtonItem(title: "Cancel", style: .plain, target: nil, action: nil) Read more >>

How to force a view controller to use light or dark mode

Example Code ...e by setting the overrideUserInterfaceStyle property of your view controller to .light or .dark. For example: class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() overrideUserInterfaceStyle = .dark } } This setting exists on other cont... Read more >>

Expanding the Swift Knowledge Base

Article I've just added 270 articles to my Swift Knowledge Base, taking it up to 576 tips, techniques, and answers for Swift developers – all updated for the latest version of Xcode and Swift. Click here to browse the knowledge base b... Read more >>

How to refactor massive view controllers

Article ...a, which meant if we added more screens to this app – bookmarks, filters, or related projects, for example – we'd need to copy and paste this method. So, clearly a better idea is to move it someplace else, but where? There are two commonly accepted options: Create a view model wrapper around thi... Read more >>

The Complete Guide to NavigationView in SwiftUI

Article ...choosing, but it also could be one of SwiftUI’s primitive views if you’re just prototyping. For example, this pushes directly to a text view: NavigationView { NavigationLink(destination: Text("Second View")) { Text("Hello, World!") } .navigationTitle("Navigation") } Because I... Read more >>

SwiftUI tips and tricks

Example Code ...an use a constant binding instead. This will allow you to use the object with a realistic value. For example, this creates a text field with the constant string “Hello”: TextField("Example placeholder", text: .constant("Hello")) .textFieldStyle(.roundedBorder) Important: If you’re using Xco... Read more >>

How to move view code out of your view controllers

Article ...at’s loosely coupled too. Rather than discuss all this in the abstract, let’s look at a specific example of how folks mix up views and view controllers. Cast your eyes over this monstrosity: backgroundColor = UIColor(white: 0.9, alpha: 1) let stackView = UIStackView() stackView.translatesAutores... Read more >>

How to detect device rotation

Example Code ...oid) -> some View { self.modifier(DeviceRotationViewModifier(action: action)) } } // An example view to demonstrate the solution struct ContentView: View { @State private var orientation = UIDeviceOrientation.unknown var body: some View { Group { if orientati... Read more >>

How to use the coordinator pattern in iOS apps

Article ... get asked when folks move to coordinators. In this article I want to provide you with a hands-on example of the coordinator pattern, which takes responsibility for navigation out of your view controllers and into a separate class. This is a pattern I learned from Soroush Khanlou – folks who’... Read more >>

5 Steps to Better SwiftUI Views

Article ...fortable with the way SwiftUI works, we are still quite a long way from agreeing best practices. For example, if you have several different ways of solving a problem, we’re still in the process of figuring out which one makes most sense for a given situation. So, we’re at this strange position wh... Read more >>

Building a UIKit user interface programmatically

Project ...iew. These rectangles have a special type called CGRect, because they come from Core Graphics. As an example, we’ll be calculating the X position for a button by multiplying our fixed button width (150) by its column position. So, for column 0 that will give an X coordinate of 150x0, which is 0, an... Read more >>

The Ultimate Guide to WKWebView

Article ...ndle, along with another URL that stores any other files you want to allow the web view to read. For example, if you wanted to load a file called "help.html" you might use code like this: if let url = Bundle.main.url(forResource: "help", withExtension: "html") { webView.loadFileURL(url, allowingR... Read more >>

What's new in Swift 5.5?

Article ...ow us to send back values after a function returns, but they had tricky syntax as you’ll see. For example, if we wanted to write code that fetched 100,000 weather records from a server, processes them to calculate the average temperature over time, then uploaded the resulting average back to a ser... Read more >>

What’s new in Swift 5.7

Article ...some keywords. In this article I want to introduce you to the major changes, providing some hands-on examples along the way so you can see for yourself what’s changing. Many of these changes are complex, and many of them are also interlinked. I’ve done my best to break things down into a sensible... Read more >>

8 Common SwiftUI Mistakes - and how to fix them

Article ...old habits, particular if you’ve come from UIKit or other user interface frameworks. As a starting example, how might you fill the screen with a red rectangle? You might write this: Rectangle() .fill(Color.red) And honestly that works great – it gets the exact result you want. But half that ... Read more >>

Why does SwiftUI use “some View” for its view type?

Project SwiftUI relies very heavily on a Swift power feature called “opaque return types”, which you can see in action every time you write some View. This means “one object that conforms to the View protocol, but we don’t want to say what.” Returning some View means even though we don’t know what view type is going back, the compiler does. That might sound small, but it has impo... Read more >>

How to build your first SwiftUI app with Swift Playgrounds

Article ...SwiftUI, and you’ll often find yourself using several at once to get exactly the right effect. For example, try changing your text to include these modifiers below: Text("Hello, world!") .font(.largeTitle) .foregroundColor(.blue) That will give the text a large font and a blue color. Yo... Read more >>

How to move data sources and delegates out of your view controllers

Article ...erent behavior at runtime – it’s a huge improvement. In this article I want to walk you through examples of getting common data sources and delegates out of view controllers in a way you should be able to apply to your own projects without much hassle. Before we begin, please use Xcode to create... Read more >>

Building a detail screen

Project ...d start with a lowercase letter, then use a capital letter at the start of any subsequent words. For example, myAwesomeVariable. This is sometimes called camel case. UIImageView!: This declares the property to be of type UIImageView, and again we see the implicitly unwrapped optional symbol: !. This ... Read more >>

Advanced coordinators in iOS

Article ...tead? I'll be giving you lots of hands-on code along the way, because I want you to see real-world examples of how these problems are solved. If you missed my earlier tutorial on the coordinator pattern, you should start there: How to use the coordinator pattern in iOS apps. Prefer video? The scr... Read more >>

How to convert a SwiftUI view to an image

Example Code ... ImageI/O framework. (Spoiler: don’t use it, it will just lead to pain.) Let’s look at a second example that is more realistic – this automatically uses the correct image scale for the device, uses @MainActor to ensure the rendering code is safe to call, carves out the view to render into its ... Read more >>

Laying out the cards: addChildViewController()

Project The first step in our project will be to lay eight cards out on the screen so that the user can tap on one. We'll be doing most of this in code, but there is a small amount of storyboard work required. Open up Main.storyboard in Interface... Read more >>

Designing our interface

Project ...ection:) – clumsy, I know, which is why most people usually just talk about the important bit, for example, "in the numberOfRowsInSection method." We wrote only one line of code in the method, which was return pictures.count. That means “send back the number of pictures in our array,” so we’r... Read more >>

The Auto Layout cheat sheet

Article ...o have a really natural form too. In the code below I’ve used childView and parentView as names of example views, where the child is placed inside the parent. Pin a child view to edges of its parent This will make the child view run to the very edges of its parent: NSLayoutConstraint.activate([ ... Read more >>

The Complete Guide to Optionals in Swift

Article ...ore experienced developers. What are optionals? Optionals represent something that has no value. For example, consider this code: let names = ["Margaret", "Matthew", "Megan"] let position = names.index(of: "Mxyzptlk") That creates an array of names and looks up the position of a name that doesn’t e... Read more >>

Swiftoberfest 2019

Article ...uld write a 100 Days of SwiftUI article, a new knowledge base article, and an addition to SwiftUI by Example – three articles every day for a month? Could I do that while also speaking at Mobiconf in Poland and Pragma Conference in Italy? More importantly, should I do that? Of course you know the ... Read more >>

Creating a secondary view for NavigationView

Project ..., some description text, and a list of facilities. Important: Like I said earlier, the content in my example JSON is mostly fictional, and this includes the photos – these are just generic ski photos taken from Unsplash. Unsplash photos can be used commercially or non-commercially without attributi... Read more >>

How to make a view dismiss itself

Example Code When you show a SwiftUI view using a sheet, it’s common to want to dismiss that view when something happens – when the user taps on a button, for example. There are two ways of solving this in SwiftUI, and I’m going to show you both so you can decide which suits your needs. The first option is to tell the view to dismiss itself using its pres... Read more >>

Learn essential Swift in one hour

Article ...ains("Octarine")) Dictionaries Dictionaries store multiple values according to a key we specify. For example, we could create a dictionary to store information about a person: let employee = [ "name": "Taylor", "job": "Singer" ] To read data from the dictionary, use the same keys you used whe... Read more >>

Advanced UIView shadow effects using shadowPath

Article ...r than our view so that the shadow is bigger than the view, and give it a fairly small height. As an example, this creates a contact shadow that’s 40 points wider than the view, and 20 points high: let shadowSize: CGFloat = 20 let contactRect = CGRect(x: -shadowSize, y: height - (shadowSize * 0.4),... Read more >>

What’s new in Swift 5.0

Article ...iples and more. Try it yourself: I created an Xcode Playground showing what's new in Swift 5.0 with examples you can edit. A standard Result type Watch the video SE-0235 introduces a Result type into the standard library, giving us a simpler, clearer way of handling errors in complex code su... Read more >>

Get started with Vapor 3 for free

Article ...mebrew will ask for your password. Now we can go ahead and create a new project for Vapor 3. In this example we’re going to build a simple web chat called WaffleSpot: users can enter a username and a message into a web form, which we’ll then save to an SQLite database. They’ll also be able to r... Read more >>

How to embed a view in a navigation view

Example Code ...leDisplayMode(), that gives us control over whether to use large titles or smaller, inline ones. For example, by default views will inherit their large title display mode from whatever view presented them, or if it’s the initial view then it will use large titles. But if you’d prefer to enable or... Read more >>

Vapor + Leaf templating cheat sheet

Article ...raws/vapor-clean cd LeafTest That creates a new Vapor project called LeafTest, asking it to clone my example project from GitHub. Don’t worry: that example project contains the absolute least amount of code required to set up a Vapor server. Adding Leaf to your project Adding Leaf takes two steps. ... Read more >>

Build your first app with SwiftUI and SwiftData

Article ...erty with @State or similar, SwiftUI automatically creates three ways of accessing the property. For example, if we had an integer called age, then: If we read age directly, we can get or set the integer. If we use $age, we access a binding to the data, which is a two-way connection to the data that... Read more >>

How to check whether an iPhone or iPad is upside down or face up

Example Code If your app needs to know the orientation of the user’s device – face up or face down – it takes only four steps to implement. First, write a method that can be called when the device orientation changes: @objc ... Read more >>

Build a unit converter for macOS

Article ...ds to store the human-readable name of the conversions – “Distance” or “Temperature”, for example – along with an array of the various measurements inside each conversion group, all of which descend from the Dimension class. You might think that could be represented using a dictionary l... Read more >>

How to render UIViews in 3D using CATransformLayer

Article ...s render multiple sublayers with a 3D transform applied. I’m going to walk through three different examples so you can get a taste of what’s possible, but first I want to show you the most important part: var perspective = CATransform3DIdentity perspective.m34 = -1 / 500 let transformLayer = CAT... Read more >>

Introducing MVVM into your SwiftUI project

Project ...ies in ContentView with a single one: @State private var viewModel = ViewModel() Tip: This is a good example of why placing view models inside extensions is helpful – we just say ViewModel and we automatically get the correct view model type for the current view. That will of course break a lot of ... Read more >>

Build a unit converter for tvOS

Article ...ork well using the Apple Remote – UISwitch, UIPickerView, UISlider, and UIStepper are absent, for example. In their place, tvOS has the focus engine: a unique way of letting users navigate around using indirect touches on their remote. For the most part this does The Right Thing, but if you develo... Read more >>

How to synchronize animations from one view to another with matchedGeometryEffect()

Example Code If you have the same view appearing in two different parts of your view hierarchy and want to animate between them – for example, going from a list view to a zoomed detail view – then you should use SwiftUI’s matchedGeometryEffect() modifier, which is a bit like Magic Move in Keynote. To use the modifier, attach it... Read more >>

Designing a single card view

Project ...g for the prompt and a string for the answer. To make our lives easier, we’re also going to add an example card as a static property, so we have some test data for previewing and prototyping. So, create a new Swift file called Card.swift and give it this code: struct Card { let prompt: String ... Read more >>

Get started with SwiftUI

Article ...n to how SwiftUI works… Update: I've released a massive, free guide to SwiftUI here: SwiftUI by Example – it contains a huge number of code samples and solutions for common SwiftUI problems, plus a long video showing you how to build your first complete project. You can also now follow my free... Read more >>

What’s new in Vapor 3?

Article ...ing architecture means that any operation that takes more than a tiny amount of time to run – for example a network request, a database request, or even rendering templates – is now run asynchronously. That is, your network request code returns immediately even though the work itself has not co... Read more >>

How to find and fix memory leaks using Instruments

Article ...t, which is designed to identify where and when memory is allocated. If you don’t already have the example project to hand, please download it and open it in Xcode. Now press Cmd+I to build and run the project for Instruments, select the allocations instrument, then press Choose. Just like with th... Read more >>

What’s new in iOS 12?

Article ...be covering it all here. In this article I'll walk you through the major changes, complete with code examples, so you can try it for yourself. Note: you will need macOS Mojave if you want to use the new Create ML tools. You might also want to read what’s new in Swift 4.2. I also published API diff... Read more >>

Using coordinators to manage SwiftUI view controllers

Project ... controllers. Remember, “delegates” are objects that respond to events that occur elsewhere. For example, UIKit lets us attach a delegate object to its text field view, and that delegate will be notified when the user types anything, when they press return, and so on. This meant that UIKit develo... Read more >>

How to create multi-column lists using Table

Example Code ...down to show just the first column of data, but on iPad and Mac they will show all their data. As an example, we might have a simple User struct like this one: struct User: Identifiable { let id: Int var name: String var score: Int } I’ve used both a String and Int for types there, bec... Read more >>

How to add advanced text styling using AttributedString

Example Code ...olors, and more. Sadly, it has a rather bafflingly opaque API so I want to show you a whole bunch of examples to help get you started. We can create an AttributedString with common properties such as font, background color, and foreground color: struct ContentView: View { var message: AttributedS... Read more >>

What’s new in Swift 5.9?

Article .... In this article I’ll walk you through the most important changes in this release, providing code examples and explanations so you can try it all yourself. You’ll need the latest Swift 5.9 toolchain installed in Xcode 14, or the Xcode 15 beta. if and switch expressions SE-0380 adds the ability f... Read more >>

How to create live playgrounds in Xcode

Example Code ...layground created by you, and only by you, demonstrating something interesting. I’m providing some example code below to help you start, but your finished submission must be your own work. Your playground must work entirely offline, and be no larger than 25MB when zipped. Apple will pay for your lo... Read more >>

How to pass data between two view controllers

Example Code ...Passing data forward is used when you want to show some information in a detail view controller. For example, view controller A might contain a list of names that the user can select, and view controller B might show some detailed information on a single name that the user selected. In this case, you... Read more >>

Recording from the microphone with AVAudioRecorder

Project ...how to navigate to a folder like the one the iOS Simulator uses, because it's hidden by default. For example, you'll get something like this: file:///Users/twostraws/Library/Developer/CoreSimulator/Devices/E470B24D-5C0C-455F-9726-DC1EAF30D5A4/data/Containers/Data/Application/D5E4C08C-2B1E-40BC-8EBE-9... Read more >>

How to push a new view onto a NavigationStack

Example Code ... and NavigationStack will care of pushing the new view on the stack for us along with animation. For example, this creates a simple DetailView struct, then presents it from a NavigationStack: struct DetailView: View { var body: some View { Text("This is the detail view") } } struct C... Read more >>

Showing and hiding views

Project ...e or false the sheet will either be presented or dismissed respectively. Let’s start with a simple example, which will be showing one view from another using a sheet. First, we create the view we want to show inside a sheet, like this: struct SecondView: View { var body: some View { Tex... Read more >>

Wrapping a UIViewController in a SwiftUI view

Project ...e advanced functionality. Sometimes this will be to integrate existing code you wrote for UIKit (for example, if you work for a company with an existing UIKit app), but other times it will be because UIKit and Apple’s other frameworks provide us with useful code we want to show inside a SwiftUI lay... Read more >>

Adding views to UIStackView with addArrangedSubview()

Project ...set our view controller to be the web view's delegate, add it to the stack view, then point it at an example URL to get things started. First, add an import for WebKit so we can use WKWebView: import WebKit Now here’s the code for addWebView() – put this into ViewController.swift, just below s... Read more >>

How to return different view types

Example Code The body property of any SwiftUI automatically gets the ability to return different views thanks to a special attributed called @ViewBuilder. This is implemented using Swift’s result builder system, and it understands how to present ... Read more >>

5 new Xcode tips and tricks to help you work faster

Article ... can show you what your current view controller looks like in any number of alternative layouts. For example, you could be designing for iPhone 8 in portrait, and have IB show you iPhone 8 landscape, iPhone X, iPad Pro 12.9-inch in portrait, and iPad Pro 9.7-inch in landscape with split view – all... Read more >>

15 tips to optimize your SpriteKit game

Article ...ltiple texture atlases to fit your actual content: all the animations for a player in one atlas, for example, and all the sprites for a particular world in another. 2. Preload textures as needed It shouldn’t surprise you when I say that there is a performance cost to loading textures from your app ... Read more >>

Reading custom values from the environment with @EnvironmentObject

Project ...utes a child, because what environment objects a view has access to depends on its parent views. For example, if view A has access to an environment object and view B is inside view A – i.e., view B is placed in the body property of A – then view B also has access to that environment object. This... Read more >>

The Complete Guide to SF Symbols

Article ...??bell.slash” – but in SwiftUI there’s a symbolVariant() modifier that makes this easier. For example, this renders a bell icon with a slash through it: Image(systemName: "bell") .symbolVariant(.slash) And this surrounds the bell with a square: Image(systemName: "bell") .symbolVariant(... Read more >>

How to fix “Modifying state during view update, this will cause undefined behavior”

Example Code ... see right now might change in the future because it’s not how SwiftUI should be used. Here’s an example of the problem in action: struct ContentView: View { @State private var name = "" var body: some View { if name.isEmpty { name = "Anonymous" } ret... Read more >>

How to find and fix slow drawing using Instruments

Article ...elp us identify and resolve drawing issues, and I want to walk you through some of them using a real example. This is a topic I talk about a lot – see here for example – because it really matters, and every time I speak or write about it some folks learn it for the first time. First, you need to... Read more >>

Formatting our mission view

Project Now that we have all our data in place, we can look at the design for our first screen: a grid of all the missions, next to their mission badges. The assets we added earlier contain pictures named “apollo1@2x.png” and similar, which means they are accessible in the asset catalog asapollo1”, “apollo12”, an... Read more >>

Auto Layout in code: addConstraints with Visual Format Language

Project Create a new Single View App project in Xcode, naming it Project6b. We're going to create some views by hand, then position them using Auto Layout. Put this into your viewDidLoad() method: override func viewDidLoad() { super.viewDidLoad() let label1 = UILabel() label... Read more >>

How to add a gesture recognizer to a view

Example Code ...o trigger the gesture, then attach an onEnded closure that will be run when the gesture happens. For example, this creates an image that gets smaller every time it’s tapped: struct ContentView: View { @State private var scale = 1.0 var body: some View { Image("ireland") ... Read more >>

How to dynamically adjust the appearance of a view based on its size and location

Example Code ...ame-like things such as the offset and scale of your view, because they don’t affect layout. As an example, the following code blurs each view in a scroll view by some blur amount that’s calculated by how far away the view is away from the center of its scroll view. That means views near the vert... Read more >>

How to refactor your app to add unit tests

Article ...s mistakes and problems that we’ll be examining over this tutorial series. If you’re looking for example code to learn from, this is the wrong place. To get started, download the project from GitHub here. The app is designed to store and display famous quotes, and I recommend you give it a quick ... Read more >>

Super-powered string interpolation in Swift 5.0

Article ...ou see, appendInterpolation() so that we can handle various different data types in unique ways. For example, we could write some code to handle Twitter handles, looking specifically for the twitter parameter name like this: mutating func appendInterpolation(twitter: String) { appendLiteral("@\(t... Read more >>

Understanding frames and coordinates inside GeometryReader

Project ...s is let us read the size that was proposed by the parent, then use that to manipulate our view. For example, we could use GeometryReader to make a text view have 90% of all available width regardless of its content: struct ContentView: View { var body: some View { GeometryReader { geo in... Read more >>

Switching view states with enums

Project ...this solution. The first is to define an enum for the various view states you want to represent. For example, you might define this as a nested enum: enum LoadingState { case loading, success, failed } Next, create individual views for those states. I’m just going to use simple text views here,... Read more >>

How to scan a QR code

Example Code iOS has built-in support for scanning QR codes using AVFoundation, but the code isn't easy: you need to create a capture session, create a preview layer, handle delegate callbacks, and more. To make it easier for you, I've created a UIViewController subclass that does all the hard work for you – yo... Read more >>

What’s new in Swift 5.4?

Article ... of them. Swift has always had the ability to use implicit member syntax for simple expressions, for example if you wanted to color some text in SwiftUI you could use .red rather than Color.red: struct ContentView1: View { var body: some View { Text("You're not my supervisor!") ... Read more >>

How to run an asynchronous task when a view is shown

Example Code ...executed asynchronously, this is a great place to fetch some initial network data for your view. For example, if we wanted to fetch a list of messages from a server, decode it into an array of Message structs, then show it in a list, we might write something like this: struct Message: Decodable, Iden... Read more >>

How to create a snow scene with Core Animation

Article CALayer powers so much of the rendering in iOS, but it has also has lots of useful subclasses that do specialized tasks. In this article we’re going to use three of them to build a snowy scene: CAEmitterLayer to make snow fall, CAGradientLayer to draw the background sky, and CAShapeLayer to draw some natural-looking ground. The three combine to lo... Read more >>

View composition

Project ... one large view into multiple smaller views, and SwiftUI takes care of reassembling them for us. For example, in this view we have a particular way of styling text views – they have a large font, some padding, foreground and background colors, plus a capsule shape: struct ContentView: View { va... Read more >>

How to adopt iOS 11 user interface changes in your app

Article iOS 11 introduces a variety of major changes to the way apps look and work, and how they interact with the user. In fact, it’s easily the biggest set of design changes since iOS 7, and in some places actually reverses choices made in iOS 7. So... Read more >>

How to push a new view when a list row is tapped

Example Code Updated in iOS 16 SwiftUI’s NavigationLink can be used inside list rows to present new views when a row is tapped. If the NavigationLink wraps around your entire row, the system automatically understands to make the entire row tappable in order to present the new view. Th... Read more >>

Countdown to WWDC 18

Article ...e coordinator pattern in iOS apps WWDC-59: Server-side Swift: Kitura vs Vapor WWDC-58: How to render example content using prepareForInterfaceBuilder() WWDC-57: Understanding protocol associated types and their constraints WWDC-56: Controlling extension points in protocols WWDC-55: How to loop over a... Read more >>

Annotations and accessory views: MKPinAnnotationView

Project ...eed to be careful of here. First, viewFor will be called for your annotations, but also Apple's. For example, if you enable tracking of the user's location then that's shown as an annotation and you don't want to try using it as a capital city. If an annotation is not one of yours, just return nil fr... Read more >>

What’s new in Xcode 14?

Article ...it just keeps getting smarter and smarter in ways that I hadn’t even imagined were possible. As an example, let’s say we had a Player struct such as this one: struct Player: Identifiable { var id = UUID() var name: String var score = 0 } Swift will automatically generate a memberwise ... Read more >>

Sharing an observed object with a new view

Project ...nly update those views if they actually used the properties that changed. In this app, we’re going to design a view specially for adding new expense items. When the user is ready, we’ll add that to our Expenses class, which will automatically cause the original view to refresh its data so the exp... Read more >>

What’s new in Swift 5.6?

Article ...er to Swift 6. In this article I want to introduce you to the major changes, providing some hands-on examples along the way so you can see for yourself what’s changing. Tip: You can also download this as an Xcode playground if you want to try the code samples yourself. Introduce existential any ... Read more >>

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.