Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore iOS Programming: The Big Nerd Ranch Guide

iOS Programming: The Big Nerd Ranch Guide

Published by Willington Island, 2021-08-21 12:10:29

Description: iOS Programming: The Big Nerd Ranch Guide leads you through the essential concepts, tools, and techniques for developing iOS applications. After completing this book, you will have the know-how and the confidence you need to tackle iOS projects of your own. Based on Big Nerd Ranch's popular iOS training and its well-tested materials and methodology, this bestselling guide teaches iOS concepts and coding in tandem. The result is instruction that is relevant and useful. Throughout the book, the authors explain what's important and share their insights into the larger context of the iOS platform. You get a real understanding of how iOS development works, the many features that are available, and when and where to apply what you've learned.

Search

Read the Text Version

Testing VoiceOver Testing VoiceOver Open Photorama.xcodeproj. The best way to test VoiceOver is with an actual device, so we strongly recommend using a device if you have one available. If you do not have a device available, you can use the simulator. Begin by clicking the Xcode menu and choosing Open Developer Tool → Accessibility Inspector. Build and run the application; once the simulator is running the app, switch to the Accessibility Inspector and select the simulator from the target pop-up menu (Figure 24.1). Figure 24.1  Changing targets in the Accessibility Inspector Once the target has been set to the simulator, click the Start inspection follows point button on the Accessibility Inspector’s toolbar (the button with a target icon). As you mouse over and navigate in the simulator, the Accessibility Inspector will provide information about whatever element has focus on the simulator’s screen. VoiceOver is not included on the simulator, but the information shown in the Accessibility Inspector is similar. 483

Chapter 24  Accessibility If you have a device, open Settings, choose Accessibility → VoiceOver, and finally turn on VoiceOver (Figure 24.2). Figure 24.2  Enabling VoiceOver There are a couple ways to navigate with VoiceOver on. There are a couple ways to navigate with VoiceOver on. To start, slide your finger around the screen. Notice that the system speaks a description of whatever element your finger is currently over. Now tap the Back button in the top-left corner of the screen that says Accessibility. The system will tell you that this element is the “Accessibility – Back button.” The system is reading you both the accessibilityLabel as well as what is essentially the accessibilityTraits. Notice that tapping the Accessibility Back button does not take you back to the previous screen. To activate the selected item, double-tap anywhere on the screen. This corresponds to a single-tap with VoiceOver disabled. This will take you to the previous screen for Accessibility. Another way to navigate is to swipe left and right on the screen. This will select the previous and next accessible elements on the screen, respectively. The VoiceOver row should be selected. Play around with swiping left and right to move the focus around the screen. 484

Accessibility in Photorama Swipe with three fingers to scroll. Note that to scroll, the scroll view or one of its subviews must be the currently focused element. Play around with single- and double-taps to select and activate items as well as using three fingers to scroll. This is how you will navigate with VoiceOver enabled. One other gesture that is useful to know is how to enable Screen Curtain. Using three fingers, triple-tap anywhere on the screen. The entire screen will go black, allowing you to truly test and experience how your app will feel to someone with a visual impairment. Three-finger triple-tap anywhere again to turn Screen Curtain off.     Accessibility in Photorama With VoiceOver still enabled, build and run Photorama on your device to test its accessibility. Once the application is running, drag your finger around the screen. Notice that the system is playing a dulled beeping sound as you drag over the photos. This is the system’s way of informing you that it is not able to find an accessibility element under your finger. Currently, the PhotoCollectionViewCells are not accessibility elements. This is easy to fix. Open PhotoCollectionViewCell.swift and override the isAccessibilityElement property to let the system know that each cell is accessible. Listing 24.1  Making the cell accessible (PhotoCollectionViewCell.swift) override var isAccessibilityElement: Bool { get { return true } set { // Ignore attempts to set } } 485

Chapter 24  Accessibility Now build and run the application. As you drag your finger across the photos, you will hear a more affirming beep and see each cell outlined with the VoiceOver cursor (Figure 24.3). No description is spoken, but you are making progress. Figure 24.3  VoiceOver cursor Go back to PhotoCollectionViewCell.swift. You are going to add an accessibility label for VoiceOver to read when an item is selected. Currently, a cell knows nothing about the Photo that it is displaying, so add a new property to hold on to this information. Listing 24.2  Giving the cell a description (PhotoCollectionViewCell.swift) class PhotoCollectionViewCell: UICollectionViewCell { @IBOutlet var imageView: UIImageView! @IBOutlet var spinner: UIActivityIndicatorView! var photoDescription: String? 486

Accessibility in Photorama In the same file, override the accessibilityLabel to return this string. Listing 24.3  Using the description for the accessibility label (PhotoCollectionViewCell.swift) override var accessibilityLabel: String? { get { return photoDescription } set { // Ignore attempts to set } } Open PhotoDataSource.swift and update collectionView(_:cellForItemAt:) to set the photoDescription on the cell. Listing 24.4  Setting the photo description (PhotoDataSource.swift) func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let identifier = \"PhotoCollectionViewCell\" let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! PhotoCollectionViewCell let photo = photos[indexPath.row] cell.photoDescription = photo.title cell.update(displaying: nil) return cell } Build and run the application. Drag your finger over the screen and you will hear the titles for each photo. Accessibility traits inform the user how an element should be treated. Some traits include UIAccessibilityTraits.button, UIAccessibilityTraits.link, and UIAccessibilityTraits.staticText. For PhotoCollectionViewCell, a relevant trait that should be included is the UIAccessibilityTraits.image. Additionally, to communicate to the user that action can be taken on the cell, you will add the UIAccessibilityTraits.button trait. In PhotoCollectionViewCell.swift, override the accessibilityTraits property to let the system know that a cell holds an image, and that it can be tapped. Listing 24.5  Adding an accessibility trait to the cell (PhotoCollectionViewCell.swift) override var accessibilityTraits: UIAccessibilityTraits { get { return super.accessibilityTraits.union([.image, .button]) } set { // Ignore attempts to set } } 487

Chapter 24  Accessibility You are combining any traits inherited from the superclass with .image and .button. This is done using union(_:), which joins all the members of two sets.   Build and run the application. Notice that the new traits you added are spoken when you select a cell. You might also notice that sometimes an actual description of the image is spoken. This is Apple being smart about the .image trait and using computer vision to attempt to further describe the image. The remaining parts of the application are mostly accessible because they use standard views and controls. The only thing you need to update is the image view when drilling down to a specific Photo. You can customize many views’ accessibility information from within storyboards, and you will be able to do that for the image view. Open Main.storyboard and navigate to the scene associated with the PhotoInfoViewController. Select the image view and open its identity inspector. Scroll to the bottom, to the section labeled Accessibility. Check the Enabled checkbox at the top of this section to enable accessibility for this image view and uncheck the User Interaction Enabled checkbox (Figure 24.4). Figure 24.4  Updating the accessibility options 488

Accessibility in Photorama Open PhotoInfoViewController.swift and update viewDidLoad() to give the image view a more meaningful accessibility label. Listing 24.6  Setting the image’s accessibility label (PhotoInfoViewController.swift) override func viewDidLoad() { super.viewDidLoad() imageView.accessibilityLabel = photo.title Build and run the application and navigate to a specific photo. You will notice that with this small addition, this entire screen is accessible. Finally, turn your attention to the TagsViewController. While still running the application, drill down to the TagsViewController. Add a tag to the table view if one is not already present. Select a row in the table and notice that VoiceOver reads the name of this tag; however, there is no indication to users that they can toggle the checkmark for each row. Open TagDataSource.swift and update the cell’s accessibility hint and traits in tableView(_:cellForRowAt:). Listing 24.7  Giving the cell an accessibility hint and traits (TagDataSource.swift) func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: \"UITableViewCell\", for: indexPath) let tag = tags[indexPath.row] cell.textLabel?.text = tag.name cell.accessibilityHint = \"Toggles selection\" cell.accessibilityTraits = [.button] return cell } Build and run the application and marvel at its accessibility. One of the most common reasons developers cite for not making their apps more accessible is lack of awareness about the topic. Be mindful of supporting VoiceOver, and other accessibility features, during all stages of iOS development, and you will make apps that are accessible to a wider audience. You can learn more about the ways iOS and other Apple platforms are accessible to users by visiting www.apple.com/accessibility/. To learn how to take advantage of these capabilities as a developer, check out developer.apple.com/accessibility/. Congratulations! Over the past five chapters, you have worked on a rather complex app. Photorama is able to make multiple web service calls, display photos in a grid, cache image data to the filesystem, and persist photo data using Core Data. On top of all that, it is accessible to users with visual impairments. To accomplish this, you used knowledge that you have gained throughout this book, and you applied that knowledge to create an awesome app that is also robust and maintainable. It was hard work, and you should be proud of yourself. 489

Chapter 24  Accessibility Bronze Challenge: VoiceOver Pronunciation Sometimes VoiceOver struggles with the pronunciation of some words. In these cases, it can be useful to provide VoiceOver with a phonetic spelling. Update the navigation item for PhotosViewController to provide a phonetic spelling for “Photorama.” 490

25 Afterword Welcome to the end of the book! You should be very proud of all your work and all that you have learned. Now there is good news and bad news: • The good news: The stuff that leaves programmers befuddled when they come to the iOS platform is behind you now. You are an iOS developer. • The bad news: You are probably not a very good iOS developer. What to Do Next It is now time to make some mistakes, read some really tedious documentation, and be humbled by the heartless experts who will ridicule your questions. Here is what we recommend: Write apps now. If you do not immediately use what you have learned, it will fade. Exercise and extend your knowledge. Now. Go deep. This book has consistently favored breadth over depth; any chapter could have been expanded into an entire book. Find a topic that you find interesting and really wallow in it – do some experiments, read Apple’s docs on the topic, and read postings on blogs and StackOverflow. Connect. There are iOS Developer Meetups in most cities, and the talks are surprisingly good. There are CocoaHeads chapters around the world. There are discussion groups online. If you are doing a project, find people to help you: designers, testers (AKA guinea pigs), and other developers. Make mistakes and fix them. You will learn a lot on the days when you say, “This application has become a ball of crap! I’m going to throw it away and write it again with an architecture that makes sense.” Polite programmers call this refactoring. Give back. Share the knowledge. Answer a dumb question with grace. Give away some code. Shameless Plugs Keep an eye out for other guides from Big Nerd Ranch. We also offer week-long courses for developers. And if you just need some code written, we do contract programming. For more information, visit our website at www.bignerdranch.com. You, dear reader, make our lives of writing, coding, and teaching possible. So thank you for buying our book. 491



Index damping ratio, 386 property animators, 384 Symbols spring, 386 timing functions, 385 #column expression, 166 triggering, 384 #file expression, 166 anti-aliasing, 81 #function expression, 166, 286 App ID, 32 #line expression, 166 append(_:) method, 43 $0, $1... (shorthand argument names), 362 application bundle %H (breakpoint hit count), 174 about, 288, 289 .atomic, 277 internationalization and, 157 .xcassets (Asset Catalog), 29 localization and, 142 .xcdatamodeld (data model file), 446 application sandbox, 271, 272, 288 // MARK:, 327 applications == operator, 434 (see also application bundle, debugging, @discardableResult, 190 projects) @escaping annotation, 409 building, 14 @IBAction, 21 data storage, 271, 272 @IBOutlet, 19, 237-239 deploying, 32-34 @NSManaged keyword, 450 directories in, 271, 272 @objc annotation, 111, 280 icons for, 28-30 launch images for, 31 A multiple threads in, 414 running on simulator, 14 access control, 373 archiving accessibility for application data, 271 Core Data vs, 443 adding accessibility hints, 489 arrays, Array type adding accessibility labels, 486 about, 36, 40, 41 creating accessibility elements, 485 count property, 43 setting accessibility information in filter(_:), 411 storyboards, 488 forEach(_:), 362 setting accessibility traits, 487 literal, 41 UIAccessibility protocol, 482 map(_:), 361 VoiceOver, 482, 484 sort(by:), 50 Accessibility Inspector, 483 subscripting, 41 accessory view (UITableViewCell), 194 Asset Catalog action methods about, 29 about, 21 adding colors to, 340 implementing, 26 adding images to, 30 activity indicators, 427 assets addSubview(_:) method, 58 about, 29, 82, 92 alert controllers, 299 accessing programmatically, 353-356 alerts, 299 asynchronous processes, 408 alignment rectangle, 68, 69 .atomic, 277 anchors, 105 attributes (Core Data), 444 animations attributes inspector (Xcode), 65 about, 383-389 Auto Layout animating colors, 387 493

Index (see also views) customizing layout, 424 about, 15-18 alignment rectangle, 68, 69 dynamic cell heights, 219 autoresizing masks and, 113, 114 constraints, 15, 17 prototype, 198 (see also constraints) CGPoint type, 57 dynamic cell heights, 219 CGRect type, 57-59 layout attributes, 68 CGSize type, 57 nearest neighbor and, 70 characters, Character type, 36 purpose of, 68 class methods, 36 autoresizing masks, 104, 113, 114 classes B (see also types) background state, 274-276, 286, 287 base internationalization, 142 Bundle, 142, 157 baselines, 68 Data, 322 becomeFirstResponder() method, 124 DateFormatter, 241 Booleans, Boolean type, 36, 39 IndexPath, 196, 208 breakpoints JSONDecoder, 403-406 JSONEncoder, 266, 403 adding actions to, 173 NotificationCenter, 278 advancing through code, 171 NSCache, 317 breakpoint hit count (%H), 174 NSFetchRequest, 455 deleting, 172 NSLayoutConstraint, 109 exception, 176 NSManagedObject, 450 setting, 168 NumberFormatter, 129 symbolic, 177 open access level, 373 using to log to the console, 174 OperationQueue, 414 bundles, Bundle class PropertyListEncoder, 266, 267 (see also application bundle) public access level, 373 about, 142, 157 SceneDelegate, 191 identifiers for, 32 UIActivityIndicatorView, 427 buttons UIAlertAction, 300 (see also target-action pairs, UIBarButtonItem UIAlertController, 299 class, views) UIBarButtonItem (see UIBarButtonItem adding to navigation bars, 261 class) camera, 297 UICollectionViewCell, 427-430 C UICollectionViewFlowLayout, 420-426 UICollectionViewLayout, 424 caches, 317 UIColor, 58 callbacks, 130 UIControl (see UIControl class) UIGestureRecognizer (see (see also delegation, target-action pairs) UIGestureRecognizer class) camera UIImagePickerController (see UIImagePickerController class) (see also images) UIImageView, 306, 307 requesting permission to access, 314, 315 UINavigationBar, 248, 251-263 cells UINavigationController (see (see also UITableViewCell class) UINavigationController class) changing cell class, 215 UINavigationItem, 258-262 UIScene, 273 UIStackView, 227-233 494

Index UIStoryboardSegue, 234-243 if-let, 45 UITabBarController (see switch, 48 UITabBarController class) connections UITabBarItem, 91-93 connections inspector, 23 UITableView (see UITableView class) in Interface Builder, 19-24 UITableViewCell (see UITableViewCell console class) interpreting messages, 161 UITableViewController (see literal expressions for debugging, 166 UITableViewController class) printing to, 132 UITapGestureRecognizer, 124 viewing in playground, 45 UITextField (see UITextField class) constants, 25, 38 UIToolbar, 260, 296 constraint(equalTo:) method, 105 constraints (see also toolbars) about, 15, 69 UITraitCollection, 338 activating programmatically, 106, 107 UIView (see UIView class) Add New Constraints Auto Layout menu, 71, UIViewController (see UIViewController 72 class) Align Auto Layout menu, 73 UIViewPropertyAnimator, 384 alignment, 73 UIWindow (see UIWindow class) clearing, 17, 76 URLComponents, 396 collection views, 420 URLRequest, 398-400, 417, 418 creating in Interface Builder, 71-74, 144 URLSession, 398-400 creating programmatically, 104-110, 373 URLSessionDataTask, 399-401, 414 implicit, 229 URLSessionDownloadTask, 399 isActive property for programmatic URLSessionTask, 398-401, 417 constraints, 106 URLSessionUploadTask, 399 resolving unsatisfiable, 113 UserDefaults, 271 content compression resistance priority, 230 UUID, 320, 321 content hugging priority, 229 closures, 50, 51, 272 contentMode property (UIImageView), 307 Codable protocol, 266 contentView (UITableViewCell), 194, 195 coders, 266 controllers, in Model-View-Controller, 6 collection views controls customizing layout, 424 about, 165 displaying, 420 custom (see custom controls) downloading image data, 432, 433 programmatic, 110 layout object, 420 Core Data setting data source, 421-424 @NSManaged keyword, 450 colors archiving vs, 443 adding to Asset Catalog, 340 attributes, 444 animating, 387 creating a persistent container, 451 background, 58 entities (see entities (Core Data)) customizing, 65 fetch requests, 455 dynamic (see dynamic colors) persistent store formats, 460 levels, 339 relationship management with, 461-480 #column expression, 166 role of, 444 common ancestor, 106 subclassing NSManagedObject, 450 concurrency, 414 Core Graphics, 81 conditionals 495

Index count property (Array), 43 enabling VoiceOver, 484 current property (Locale), 138 provisioning, 32-34 custom controls Retina display, 81, 82 screen sizes, 330 creating, 372-375 dictionaries, Dictionary type using, 376, 377 (see also JSON data) about, 36, 40, 41 D accessing, 46 literal, 41 Dark Mode, adapting to, 336-346 subscripting, 46 Data class, 322 using, 320, 321 data source methods, 193, 421, 455 directories data sources, 211 application, 271, 272 data storage Documents, 271 Library/Caches, 271 (see also archiving, Core Data) Library/Preferences, 271 for application data, 271, 272 lproj, 142, 157 with Data class, 322 tmp, 271 dataSource (UITableView), 184, 189-194 @discardableResult, 190 DateFormatter class, 241 display resolution, 59, 81 debugging do-catch statements, 269 (see also debugging tools, exceptions) document outline (Interface Builder), 8 breakpoints (see breakpoints) documentation caveman debugging, 165 opening, 383 literal expressions for, 166 for Swift, 51 LLDB console commands, 178 Documents directory, 271 stack traces, 163 doubles, Double type, 36, 39 using the console, 161 drawing (see views) debugging tools drill-down interface, 245 issue navigator, 27 dynamic colors in playgrounds, 45 about, 337 Decodable protocol, 266 creating, 340 default: (switch statement), 48 Dynamic Type, 220-223 delegation about, 130-132 E as a design pattern, 211 protocols for, 130 editButtonItem property (UITableView), 262 for UICollectionView, 432 editing property (UITableView, for UIImagePickerController, 312 UITableViewController), 200, 204 for UITableView, 184 Encodable protocol, 266 deleteRows(at:with:) method, 208 encode(_:) method (PropertyListEncoder), dependency injection, 192 268 dependency inversion principle, 192 endEditing(_:) method, 256 entities (Core Data) dequeueReusableCell(withIdentifier:for:) about, 444 method, 199 modeling, 446, 447 design patterns, 211 relationships between, 462-464 devices saving changes to, 454 checking for camera, 310-315 deploying to, 32 display resolution, 59, 81 496

enumerated() function, 46 Index enums (enumerations) forced unwrapping (of optionals), 44 about, 48 forEach(_:) method (Array), 362 associated values and, 405 foreground active state, 274 raw values and, 49 foreground inactive state, 274 switch statements and, 48 frame property (UIView), 57-59 Equatable protocol, 434 frameworks error handling with do-catch, 269 about, 58 with optionals, 269 Core Data (see Core Data) errors linking manually, 94 in playgrounds, 38 UIKit, 58 traps, 41 #function expression, 166, 286 @escaping annotation, 409 functions events (see also methods) .editingChanged, 110 callback, 130 .touchDown, 110 compared to closures, 50 .touchUpInside, 110 enumerated(), 46 .valueChanged, 110, 375 NSLocalizedString(_:comment:), 153 control, 110 event handling, 254 G touch, 254 generic type, 407 (see also touch events) genstrings, 154 exception breakpoints, 176 gestures, gesture recognizers (see exceptions, interpreting stack traces, 161 UIGestureRecognizer class) expressions, string interpolation and, 47 globally unique identifiers (GUIDs), 320 extensions H about, 353-356 naming conventions, 354 %H (breakpoint hit count), 174 header view (UITableView), 200-203 F HTTP fallthrough (switch statement), 48 methods, 417 fetch requests, 455 request specifications, 417, 418 #file expression, 166 file inspector (Xcode), 150 I file URLs, constructing, 272 fileprivate access level, 373 @IBAction, 21 filesystem, writing to, 322 @IBOutlet, 19, 237-239 filter(_:) method (Array), 411 icons first responders (see also images) about, 254-257 application, 28-30 becoming, 124 in Asset Catalog, 29 resigning, 124, 254, 256 identity inspector (Xcode), 95 Float type, 36, 39 if-let statements, 45 Float80 type, 39 image picker (see UIImagePickerController flow layouts, 424 class) for-in loops, 46 imagePickerController(_:didFinishPicking… …MediaWithInfo:) method, 312, 316 imagePickerControllerDidCancel(_:) method, 312 497

Index selecting an item when multiple items are under the cursor, 429 images setting outlets in, 20, 237 (see also camera, icons) setting target-action pairs in, 22 accessing from the cache, 321 size inspector, 64 caching, 322-324 interface files displaying in UIImageView, 306, 307 bad connections in, 239 downloading image data, 412, 432, 433 base internationalization and, 142 fetching, 318 internal access level, 373 for Retina display, 81 internationalization, 135-141, 157 saving, 316 (see also localization) storing, 317-320 intrinsic vs explicit content size, 74 inverse relationships, 464 implementation files, navigating, 325 iOS simulator (see simulator) implicit constraints, 229 iPad IndexPath class, 196, 208 (see also devices) inequality constraints, 147 application icons for, 28 init(coder:) method, 98 isEmpty property (String), 43 init(contentsOfFile:) method, 322 isSourceTypeAvailable(_:) method, 310 init(frame:) initializer, 57 issue navigator (Xcode), 27 init(nibName:bundle:) method, 98 initial view controller, 85 J initializers jpegData(compressionQuality:) method, 322 about, 42 JSON data, 402, 403 for classes vs structs, 187 JSONDecoder class, 403-406 convenience, 187 JSONEncoder class, 266, 403 custom, 187, 188 designated, 187 K free, 188 returning empty literals, 42 key-value pairs instance methods, 36 creating/using keys, 320 instance variables (see outlets, properties) in dictionaries, 40 instances, 42 in JSON data, 402 integers, Int type, 36, 39 in web services, 394 Interface Builder keyboards (see also Xcode) attributes, 121-123 adding constraints, 71 dismissing, 124, 253-257 attributes inspector, 65 Auto Layout (see Auto Layout) L bounds rectangles, 66 canvas, 8 labels connecting objects, 19-24 adding text to views, 64 connecting with source files, 216 adding to tab bar, 91 connections inspector, 23 customizing, 65 document outline, 8 updating preferred text size, 223 file inspector, 150 identity inspector, 95 language settings, 135, 150 preview, 143 (see also localization) properties and, 216 renaming UI elements, 330 launch images, 31 scenes, 9 layout attributes, 68 498

Index layout guides, 107 overriding methods to print messages to the layoutIfNeeded() method, 384 console, 94 layoutSubviews() method, 381 methods lazy loading, 84, 94, 98 (see also functions) let keyword, 38 about, 43 libraries (see frameworks) action, 21 library (Xcode), 10 addSubview(_:), 58 Library/Caches directory, 271 append(_:), 43 Library/Preferences directory, 271 becomeFirstResponder(), 124 #line expression, 166 class, 36 literal values, 41 constraint(equalTo:), 105 loadView() method, 84, 98, 103 data source, 193, 421, 455 locale property (NumberFormatter), 138 deleteRows(at:with:), 208 Locale type, current property, 138 localization dequeueReusableCell(withIdentifier:for… base internationalization and, 142 …:), 199 Bundle class, 157 encode(_:), 268 internationalization, 135-141, 157 endEditing(_:), 256 lproj directories, 142, 157 filter(_:), 411 number formatters, 138 forEach(_:), 362 strings tables, 153-156 HTTP, 417 user settings for, 135 XLIFF data type, 158 imagePickerController(_:didFinishPicki… loops examining in Value History, 47 …ngMediaWithInfo:), 312, 316 for-in, 46 imagePickerControllerDidCancel(_:), 312 in Swift, 46 init(coder:), 98 low-memory warnings, 316 init(contentsOfFile:), 322 lproj directories, 142, 157 init(nibName:bundle:), 98 instance, 36, 43 M isSourceTypeAvailable(_:), 310 jpegData(compressionQuality:), 322 main bundle, 142, 157 layoutIfNeeded(), 384 (see also application bundle) layoutSubviews()Mood, 381 loadView(), 84, 98, 103 main interface, 87 map(_:), 361 main thread, 414 open access level, 373 map(_:) method (Array), 361 overriding, 26 margins prepare(for:sender:), 242 present(_:animated:completion:), 301 accessing programmatically, 108 protocol, 133 safe area and, 359 public access level, 373 // MARK:, 327 resignFirstResponder(), 124, 254 memory management reverse(), 43 memory warnings, 316 sceneDidBecomeActive(_:), 286 UITableViewCell class, 198 sceneWillEnterForeground(_:), 286 messages sceneWillResignActive(_:), 286 in delegation design pattern, 130 selectors, 162 interpreting stack traces in the console, 161 setEditing(_:animated:), 204 literal expressions in console messages, 166 sort(by:), 50 startAnimation(), 384 499

Index static, 36 NSLocalizedString(_:comment:) function, 153 tableView(_:cellForRowAt:), 193, 196-199 @NSManaged keyword, 450 tableView(_:commit:forRowAt:), 208 NSManagedObject class, 450 tableView(_:moveRowAt:to:), 209, 210 number formatters tableView(_:numberOfRowsInSection:), 193 textFieldShouldReturn(_:), 254 for localization, 138-141 type-level, 395 to set fractional digits, 129 url(forResource:withExtension:), 157 NumberFormatter class, 129, 138 urls(for:in:), 272 numeric types viewDidAppear(_:), 98 (see also individual types) viewDidDisappear(_:), 98 about, 39 viewDidLoad() (see viewDidLoad() method) literal, 41 viewWillAppear(_:), 98, 252 viewWillDisappear(_:), 98, 252 O .mobileprovision files, 32 modal view controllers, 301, 313 @objc annotation, 280 Model-View-Controller (MVC), 6, 7, 184, 211 object graphs, 443 models, in Model-View-Controller, 6 Objective-C in iOS frameworks, 111 multithreading, 414 objects (see memory management) MVC (Model-View-Controller), 6, 7, 184, 211 open access level, 373 OperationQueue class, 414 N optionals naming conventions about, 44 cell reuse identifiers, 198 dictionary subscripting and, 46 delegate protocols, 130 forced unwrapping, 44 extensions, 354 if-let statements, 45 optional binding, 45 navigation controllers (see unwrapping, 44 UINavigationController class) outlets navigationItem (UIViewController), 258 about, 19 nearest neighbor, 70 autogenerating/connecting, 237 nil (notification wildcard), 278 connecting with source files, 216 NotificationCenter class, 278 setting, 19-21 notifications setting in Interface Builder, 235 override keyword, 26 about, 278 UIScene, 280 P UIScene.didBecomeActiveNotification, 280 UIScene.didEnterBackgroundNotification, parallel computing, 414 280 permissions, 314, 315 UIScene.didFinishLaunchingNotification, photos (see camera, images) 280 pixels (vs points), 59 UIScene.willEnterForegroundNotification, playgrounds (Xcode) 280 UIScene.willResignActiveNotification, about, 37, 38 280 errors in, 38 NSCache class, 317 Value History, 47 NSFetchRequest class, 455 viewing console in, 45 NSLayoutConstraint class, 109 pointers, in Interface Builder (see outlets) points (vs pixels), 59 predicates, 455 500

preferences, 271 Index (see also Dynamic Type, localization) UINavigationControllerDelegate, 316 prepare(for:sender:) method, 242 UITableViewDataSource, 184, 193, 194, 196, present(_:animated:completion:) method, 208, 209 301 UITableViewDelegate, 184 previewing layouts, 143 UITextFieldDelegate, 130, 254 private access level, 373 provisioning profiles, 32 processes, asynchronous, 408 pseudolanguage, 144 programmatic views public access level, 373 accessing margins, 108 Q anchors, 105 constraint(equalTo:), 105 Quartz, 81 (see Core Graphics) constraints in, 104 query items, 394 constraints, activating, 106 Quick Help (Xcode), 39 controls, 110 creating explicit constraints, 109 R isActive property on constraints, 106 layout guides, 107 Range type, 46 loadView(), 103 rawValue (enums), 49 project navigator (Xcode), 5 region settings, 135 projects relationships creating, 2-4 target settings in, 288 inverse, 464 properties to-many, 462 about, 43 to-one, 462 creating in Interface Builder, 216 reordering controls, 210 type-level, 395 resignFirstResponder() method, 124, 254 property animators, 384 resources property lists, 267, 268 about, 28, 288 property observers, 126 Asset Catalog, 29 PropertyListEncoder class, 266, 267 responders (see first responders) protocol keyword, 131 Result type, 406 protocols Retina display, 81, 82 about, 130 reuseIdentifier (UITableViewCell), 198 Codable, 266 reverse() method, 43 conforming to, 130 root view controller (UINavigationController), declaring, 130 247-249 Decodable, 266 rootViewController property (UIWindow), 87 delegate, 130-132 rows (UITableView) Encodable, 266 adding, 205, 206 Equatable, 434 deleting, 208 informal, 482 moving, 209, 210 structure of, 131 UIAccessibility, 482 S UICollectionViewDataSource, 421 UICollectionViewDelegate, 432 safe area UIImagePickerControllerDelegate, 312, about, 72 316 accessing programmatically, 107 layout guide, 107 margins and, 359 sandbox, application, 271, 272, 288 501

Index scene states, 274-276, 286, 287 isEmpty property, 43 scene(_:willConnectTo:options:) method, literal, 41 191 strings tables, 153-156 SceneDelegate class, 191 subscripting sceneDidBecomeActive(_:) method, 286 arrays, 41 scenes, 191, 273 dictionaries, 46 sceneWillEnterForeground(_:) method, 286 subviews, 54, 98 sceneWillResignActive(_:) method, 286 superview property, 60 sections (UITableView), 194 suspended state, 274, 276 segues Swift about, 35 about, 234 closures, 50 embed, 369 documentation for, 51 selectors enumerations, 36, 48 about, 162 loops, 46 unrecognized, 162 optional types in, 44 sender argument, 165 string interpolation, 46 setEditing(_:animated:) method, 204 structures, 36 sets, Set type, 36, 41 switch statements, 48 settings (see preferences) types, 36-43 shorthand argument names, 362 switch statements, 48 simulator symbolic breakpoints, 177 Accessibility Inspector, 483 enabling Dark Mode, 336 T rotating, 335 running applications on, 14 tab bar controllers (see UITabBarController sandbox location, 281 class) saving images to, 313 tab bar items, 91-93 viewing application bundle in, 288 table view cells (see UITableViewCell class) size classes, 330-335 table view controllers (see size inspector (Xcode), 64 UITableViewController class) sort descriptors (NSFetchRequest), 455 table views (see UITableView class) sort(by:) method, 50 tables (database), 444 sourceType property tableView(_:cellForRowAt:) method, 193, (UIImagePickerController), 308-312 196-199 stack traces, interpreting, 163 tableView(_:commit:forRowAt:) method, 208 stack views tableView(_:moveRowAt:to:) method, 209, 210 about, 225-233 configuring programmatically, 372 tableView(_:numberOfRowsInSection:) distributing contents, 229-231 nested, 232 method, 193 startAnimation() method, 384 target-action pairs states, scene, 274-276, 286, 287 static keyword, 395 about, 21, 22, 211 static methods, 36 creating programmatically, 111 strings, String type targets, build settings for, 288 about, 36 text internationalizing, 153 (see also Auto Layout, labels) interpolation, 47 changing preferred size, 222 customizing appearance, 66, 118 customizing size, 66 502

dynamic styling of, 221 Index input, 115-125 textFieldShouldReturn(_:) method, 254 UITableViewCellStyle, 195 threads, 414 throws keyword, 269 U timing functions, 385 tint UI thread, 414 about, 343 UIAccessibility protocol, 482 setting programmatically, 379 UIActivityIndicatorView class, 427 setting via interface files, 343 UIAlertAction class, 300 tmp directory, 271 UIAlertController class, 299 to-many relationships, 462 UIBarButtonItem class, 260-262 to-one relationships, 462 UICollectionViewCell class, 427-430 toolbars UICollectionViewDataSource protocol, 421 adding buttons to, 296 UICollectionViewDelegate protocol, 432 adding to UI, 294 UICollectionViewFlowLayout class, 420-426 topViewController property UICollectionViewLayout class, 424 (UINavigationController), 247 UIColor class, 58 touch events, 254 UIControl class, subclassing, 372-377 trait collections, 338 UIControl.Event type traps, 41 try keyword, 269 .editingChanged, 110 tuples, 46 .touchDown, 110 types .touchUpInside, 110 Array, 36, 40 .valueChanged, 110, 375 Bool, 36, 39 about, 110 CGPoint, 57 UIGestureRecognizer class, subclasses, 124 CGRect, 57 UIImage class (see images, UIImageView class) CGSize, 57 UIImagePickerController class Character, 36 instantiating, 308-312 codable, 266 presenting, 313-316 Dictionary, 36, 40 UIImagePickerControllerDelegate protocol, Double, 36, 39 312, 316 Float, 36, 39 UIImageView class, 306, 307 Float80, 39 UIKit framework, 58 generic, 407 UINavigationBar class, 248, 251-263 hashable, 40 UINavigationController class initializers, 42, 43 (see also view controllers) instances of, 42 about, 247-250 Int, 36, 39 adding view controllers to, 252 Locale, 138 instantiating, 249 Range, 46 managing view controller stack, 247 Result, 406 root view controller, 247, 248 Set, 36, 41 in storyboards, 234 specifying, 39 topViewController property, 247, 248 String, 36 UINavigationBar class and, 258-262 type inference, 39 UITabBarController vs, 246 UIControl.Event, 110 view, 248 viewControllers property, 247 viewWillAppear(_:), 252 viewWillDisappear(_:), 252 503

Index UINavigationControllerDelegate protocol, 316 subclassing, 213-223 UINavigationItem class, 258-262 UIScene class, 273 textLabel property, 195 UIScene.didActivateNotification, 280 UITableViewCell.EditingStyle.delete, 208 UIScene.didDisconnectNotification, 280 UITableViewCellStyle type, 195 UIScene.didEnterBackgroundNotification, UITableViewController class 280 (see also UITableView class) UIScene.willConnectNotification, 280 about, 184 UIScene.willDeactivateNotification, 280 UIScene.willEnterForegroundNotification, adding rows, 205, 206 280 data source methods, 193 UIStackView class, 227-233 UIStoryboardSegue class, 234-243 dataSource property, 189-194 UITabBarController class deleting rows, 208 implementing, 88-93 editing property, 204 moving rows, 209, 210 UINavigationController vs, 245 view, 90 returning cells, 196, 197 UITabBarItem class, 91-93 UITableView class subclassing, 185 (see also UITableViewCell class, UITableViewController class) UITableViewDataSource protocol, 184, 193, 194, about, 181-184 196, 208, 209 adding rows, 205, 206 UITableViewDelegate protocol, 184 UITapGestureRecognizer class, 124 dataSource property, 184 UITextField class delegation, 184 configuring, 116 deleting rows, 208 as first responder, 254 editing mode, 200, 204, 214, 262 keyboard and, 253 editing property, 200, 204 footer view, 200 UITextFieldDelegate protocol, 130, 254 UIToolbar class, 260, 296 header view, 200-203 (see also toolbars) moving rows, 209, 210 UITraitCollection class, 338 populating, 189-197 UIView class sections, 194 (see also UIViewController class, views) about, 54 tableView(_:cellForRowAt:), 193, 196-199 tableView(_:numberOfRowsInSection:), 193 animation documentation, 383 view, 186 UITableView.automaticDimension constant, 219 frame property, 57-59 UITableViewCell class layoutMargins property, 108 (see also cells) layoutMarginsGuide property, 108 safeAreaLayoutGuide property, 107 about, 194, 213 superview, 60 accessory view, 194 translatesAutoresizingMaskIntoConstraints cell styles, 195 property, 104 contentView, 194, 195 UIViewController class detailTextLabel property, 195 (see also UIView class, view controllers) imageView, 195 init(coder:), 98 retrieving instances of, 196, 197 init(nibName:bundle:), 98 loadView, 103 reuseIdentifier property, 198 loadView(), 98 reusing instances of, 198, 199 loadView() method, 84 navigationItem property, 258 present(_:animated:completion:) method, 301 504

tabBarItem property, 91 Index view, 84, 98 viewDidAppear(_:), 98 modal, 313 viewDidDisappear(_:), 98 modal presentation, 291 viewDidLoad(), 98 navigating between, 234 viewWillAppear(_:), 98 presentation styles, 302 viewWillDisappear(_:), 98 presenting modally in code, 301 UIViewPropertyAnimator class, 384 root, 247 UIWindow class segues, 234 about, 54 stack, 247 rootViewController, 87 tab bar controllers and, 88 unattached state, 274 view hierarchy and, 84 universally unique identifiers (UUIDs), 320 view hierarchy unrecognized selector error, 162 about, 54-63 url(forResource:withExtension:) method, configuring programmatically, 373 157 view property (UIViewController), 84 URLComponents class, 396 viewControllers (UINavigationController), URLRequest class, 398-400, 417, 418 247 URLs, 394 viewDidAppear(_:) method, 98 urls(for:in:) method, 272 viewDidDisappear(_:) method, 98 URLSession class, 398-400 viewDidLoad() method, 58, 98 URLSessionDataTask class, 399-401, 414 views URLSessionDownloadTask class, 399 (see also Auto Layout, touch events, UIView URLSessionTask class, 398-401, 417 class, view controllers) URLSessionUploadTask class, 399 about, 54 user interface animating, 383 (see also Auto Layout, views) appearing/disappearing, 252 drill-down, 245 autoresizing masks, 104 keyboard, 253 container views, 15 scenes, 191, 273 content compression resistance priorities, 230 window scenes, 191 content hugging priorities, 229 user settings (see preferences) creating programmatically (see programmatic UserDefaults class, 271 views) UUID class, 320, 321 drawing to screen, 55 hierarchy, 54, 55 V layers and, 55 layout guides, 107 var keyword, 38 lazy loading, 84, 94 variables, 25, 38 margins, 108 misplaced, 75 (see also instance variables, properties) in Model-View-Controller, 6 view (UIViewController), 98 presenting modally, 301, 313 view controllers removing from storyboard, 102 rendering, 55 (see also UIViewController class, views) resizing, 307 allowing access to image store, 318 scroll, 420 container view controllers, 356 size and position of, 57-59 initial, 85 stack views (see stack views) interacting with, 98 subviews, 54-63 lazy loading of views, 84, 94, 98 viewWillAppear(_:) method, 98, 252 505

Index viewWillDisappear(_:) method, 98, 252 VoiceOver, 482, 484 W web services about, 392 HTTP request specifications and, 417, 418 with JSON data, 402, 403 requesting data from, 394-401 URLSession class and, 398-401 where clauses, 407 write(to:options:) method (Data), 277 X .xcassets (Asset Catalog), 29 .xcdatamodeld (data model file), 446 Xcode (see also debugging tools, Interface Builder, projects, simulator) Asset Catalog, 29 attributes inspector, 65 Auto Layout (see Auto Layout) breakpoint navigator, 168 connections inspector, 23 creating projects, 2-4 debug area, 169 debug bar, 171 documentation, 383 editor area, 5, 8 file inspector, 150 identity inspector, 95 inspector area, 23 issue navigator, 27 library, 10 navigator area, 4 navigators, 4 opening a second editor pane, 235 organizing files with // MARK:, 327 playgrounds, 37, 38 project navigator, 5 Quick Help, 39 schemes, 14 size inspector, 64 source editor jump bar, 325 versions, 2 workspace, 4 XLIFF data type, 158 506

At Big Nerd Ranch, we create elegant, authentically useful solutions through best-in-class development and training.   CLIENT SOLUTIONS Big Nerd Ranch designs, develops and deploys applications for clients of all sizes—from small start-ups to large corporations. Our in-house engineering and design teams possess expertise in iOS, Android and full-stack web application development.   TEAM TRAINING For companies with capable engineering teams, Big Nerd Ranch can provide on-site corporate training in iOS, Android, Front-End Web, Back-End Web, macOS and Design. Of the top 25 apps in the U.S., 19 are built by companies that brought in Big Nerd Ranch to train their developers.   CODING BOOTCAMPS Big Nerd Ranch offers intensive app development and design retreats for individuals. Lodging, food and course materials are included, and we’ll even pick you up at the airport! These courses are not for the faint of heart. You will learn new skills in iOS, Android, Front-End Web, Back-End Web, macOS or Design in days—not weeks.     www.bignerdranch.com

BIG NERD RANCH CODING BOOTCAMPS   Big Nerd Ranch bootcamps cover a lot of ground in just days. With our retreat-style training, we’ll subject you to the most intensive app development course you can imagine, and when you finish, you’ll be part of an elite corps: the few, the proud, the nerds. Our distraction-free training gives you the opportunity to master new skills in an intensive environment—no meetings, no phone calls, just learning.   Big Nerd Ranch’s training was unlike any other class I’ve had. I learned skills that make me exceptionally more valuable, giving me a leg up on the competition. Since my first Big Nerd Ranch class, I’ve written software used in The White House, held positions at AT&T and Disney—and ultimately landed at Apple. —Josh Paul, Alumnus   We offer classes in iOS, Android, Front-End Web, Back-End Web, macOS and Design. Use code BNRGUIDE100 for $100 off a bootcamp of your choice.   www.bignerdranch.com


Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook