Matt Neuburg Covers iOS 14, Xcode 12, and Swift 5.3 Programming iOS 14 Dive Deep into Views, View Controllers, and Frameworks
(This page has no text content)
Matt Neuburg Boston Programming iOS 14 Dive Deep into Views, View Controllers, and Frameworks ELEVENTH EDITION
978-1-492-09217-9 [MBP] Programming iOS 14, Eleventh Edition by Matt Neuburg Copyright © 2021 Matt Neuburg. All rights reserved. Printed in Canada. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://oreilly.com). For more information, contact our corporate/institu‐ tional sales department: 800-998-9938 or corporate@oreilly.com. Editors: Rachel Roumeliotis and Suzanne McQuade Indexer: Matt Neuburg Production Editor: Kristen Brown Cover Designer: Karen Montgomery Proofreader: O’Reilly Production Services Interior Designer: David Futato Illustrator: Matt Neuburg November 2015: Sixth Edition November 2016: Seventh Edition December 2017: Eighth Edition October 2018: Ninth Edition October 2019: Tenth Edition October 2020: Eleventh Edition Revision History for the Eleventh Edition: 2020-10-08: First release See http://oreilly.com/catalog/errata.csp?isbn=9781492092179 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Programming iOS 14, the cover image of a kingbird, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a trademark claim, the designations have been printed in caps or initial caps. While the publisher and the author have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the author disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights.
Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxi Part I. Views 1. Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 Window and Root View 4 Window Scene Architecture 4 How an App Launches 6 App Without a Storyboard 7 Referring to the Window 8 Experimenting with Views 9 Subview and Superview 10 Color 13 Visibility and Opacity 14 Frame 15 Bounds and Center 17 Transform 21 Transform3D 25 Window Coordinates and Screen Coordinates 27 Trait Collections 28 Interface Style 29 Size Classes 31 Overriding Trait Collections 32 Layout 32 Autoresizing 34 Autolayout and Constraints 36 Implicit Autoresizing Constraints 39 Creating Constraints in Code 40 Constraints as Objects 46 iii
Margins and Guides 48 Intrinsic Content Size 54 Self-Sizing Views 56 Stack Views 57 Internationalization 60 Mistakes with Constraints 61 Configuring Layout in the Nib 64 Autoresizing in the Nib 65 Creating a Constraint 65 Viewing and Editing Constraints 67 Problems with Nib Constraints 69 Varying the Screen Size 71 Conditional Interface Design 72 Xcode View Features 75 View Debugger 75 Previewing Your Interface 76 Designable Views and Inspectable Properties 76 Layout Events 79 2. Drawing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 Images and Image Views 81 Image Files 82 Image Views 88 Resizable Images 90 Transparency Masks 93 Reversible Images 95 Graphics Contexts 96 Drawing on Demand 98 Drawing a UIImage 99 UIImage Drawing 100 CGImage Drawing 103 Snapshots 105 CIFilter and CIImage 106 Blur and Vibrancy Views 111 Drawing a UIView 113 Graphics Context Commands 115 Graphics Context Settings 115 Paths and Shapes 116 Clipping 120 Gradients 121 Colors and Patterns 123 Graphics Context Transforms 125 iv | Table of Contents
Shadows 127 Erasing 128 Points and Pixels 129 Content Mode 130 3. Layers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133 View and Layer 134 Layers and Sublayers 135 Manipulating the Layer Hierarchy 138 Positioning a Sublayer 139 CAScrollLayer 140 Layer and Delegate 141 Layout of Layers 141 Drawing in a Layer 142 Drawing-Related Layer Properties 144 Content Resizing and Positioning 145 Layers that Draw Themselves 148 Transforms 148 Affine Transforms 149 3D Transforms 151 Depth 151 Further Layer Features 155 Shadows 155 Borders and Rounded Corners 156 Masks 157 Layer Efficiency 158 Layers and Key–Value Coding 159 4. Animation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163 Drawing, Animation, and Threading 164 Image View and Image Animation 166 View Animation 168 A Brief History of View Animation 168 Property Animator Basics 169 View Animation Basics 172 View Animation Configuration 175 Timing Curves 180 Cancelling a View Animation 183 Frozen View Animation 186 Custom Animatable View Properties 187 Keyframe View Animation 188 Transitions 191 Table of Contents | v
Implicit Layer Animation 194 Animatable Layer Properties 194 Animating a Custom Layer Subclass 195 Animation Transactions 196 Media Timing Functions 198 Core Animation 198 CABasicAnimation and Its Inheritance 199 Using a CABasicAnimation 201 Springing Animation 204 Keyframe Animation 204 Making a Property Animatable 206 Grouped Animations 207 Animating Multiple Layers 211 Freezing an Animation 212 Transitions 213 Animations List 214 Actions 216 What an Action Is 217 Action Search 217 Hooking Into the Action Search 219 Making a Custom Property Implicitly Animatable 222 Nonproperty Actions 223 Emitter Layers 224 CIFilter Transitions 230 UIKit Dynamics 232 The Dynamics Stack 232 Custom Behaviors 236 Animator and Behaviors 238 Motion Effects 245 Animation and Layout 246 5. Touches. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249 Touch Events and Views 250 Receiving Touches 252 Restricting Touches 254 Interpreting Touches 255 Gesture Recognizers 259 Gesture Recognizer Classes 260 Gesture Recognizer States 263 Gesture Recognizer Examples 263 Gesture Recognizer Conflicts 266 Gesture Recognizer Delegate 268 vi | Table of Contents
Subclassing Gesture Recognizers 270 Gesture Recognizers in the Nib 273 Touch Delivery 273 Hit-Testing 274 Performing Hit-Testing 275 Hit-Test Munging 276 Hit-Testing for Layers 277 Hit-Testing for Drawings 278 Hit-Testing During Animation 279 Initial Touch Event Delivery 281 Gesture Recognizer and View 282 Touch Exclusion Logic 283 Gesture Recognition Logic 284 Part II. Interface 6. View Controllers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289 View Controller Responsibilities 290 View Controller Hierarchy 291 Automatic Child View Placement 294 Manual Child View Placement 295 Presented View Placement 297 Ensuring a Coherent Hierarchy 299 View Controller Creation 300 How a View Controller Obtains Its View 301 Manual View 303 Generic Automatic View 304 View in a Separate Nib 305 Summary 308 How Storyboards Work 308 How a Storyboard View Controller Nib is Loaded 309 How a Storyboard View Nib is Loaded 311 View Resizing 311 View Size in the Nib Editor 312 Bars and Underlapping 312 Resizing and Layout Events 316 Rotation 318 Uses of Rotation 318 Permitting Compensatory Rotation 319 Initial Orientation 321 Detecting Rotation 321 Table of Contents | vii
View Controller Manual Layout 322 Initial Manual Layout 322 Manual Layout During Rotation 323 Presented View Controller 325 Presentation and Dismissal 325 Configuring a Presentation 328 Communication with a Presented View Controller 334 Adaptive Presentation 336 Presentation, Rotation, and the Status Bar 338 Tab Bar Controller 339 Tab Bar Items 339 Configuring a Tab Bar Controller 341 Navigation Controller 343 Bar Button Items 345 Navigation Items and Toolbar Items 347 Configuring a Navigation Controller 350 Custom Transition 354 Noninteractive Custom Transition Animation 355 Interactive Custom Transition Animation 360 Custom Presented View Controller Transition 365 Transition Coordinator 371 Page View Controller 372 Preparing a Page View Controller 373 Page View Controller Navigation 375 Other Page View Controller Configurations 378 Container View Controllers 379 Adding and Removing Children 380 Status Bar, Traits, and Resizing 384 Previews and Context Menus 386 Context Menu Interaction and Configuration 386 Configuring the Preview 388 Configuring the Menu 390 Storyboards 391 Triggered Segues 396 Container Views and Embed Segues 401 Storyboard References 402 Unwind Segues 403 View Controller Lifetime Events 407 Order of Events 409 Appear and Disappear Events 410 Event Forwarding to a Child View Controller 410 View Controller Memory Management 412 viii | Table of Contents
Lazy Loading 413 NSCache, NSPurgeableData, and Memory-Mapping 414 Background Memory Usage 415 7. Scroll Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417 Content Size 417 Creating a Scroll View in Code 418 Manual Content Size 418 Automatic Content Size with Autolayout 419 Scroll View Layout Guides 420 Using a Content View 422 Scroll View in a Nib 425 Content Inset 428 Scrolling 430 Scrolling in Code 432 Paging 433 Tiling 434 Zooming 437 Zooming Programmatically 438 Zooming with Detail 439 Scroll View Delegate 442 Scroll View Touches 444 Floating Scroll View Subviews 448 Scroll View Performance 449 8. Table Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 451 Table View Controller 453 Table View Cells 455 Built-In Cell Styles 456 Registering a Cell Class 462 Custom Cells 466 Table View Data 472 The Three Big Questions 473 Reusing Cells 475 Self-Configuring Cells 477 Apple’s Cell Configuration Architecture 478 Table View Sections 484 Section Headers and Footers 485 Table View Section Example 488 Section Index 491 Variable Row Heights 492 Manual Row Height Measurement 493 Table of Contents | ix
Measurement and Layout with Constraints 494 Estimated Height 495 Automatic Row Height 496 Table View Selection 498 Managing Cell Selection 498 Responding to Cell Selection 499 Navigation from a Table View 501 Table View Scrolling and Layout 502 Refreshing a Table View 503 Cell Choice and Static Tables 505 Direct Access to Cells 506 Refresh Control 507 Editing a Table View 509 Toggling a Table View’s Edit Mode 509 Edit Mode and Selection 511 Changing a Table View’s Structure 512 Deleting a Cell 513 Deleting Multiple Cells 515 Table View Diffable Data Source 516 Populating a Diffable Data Source 518 Subclassing a Diffable Data Source 520 Changing a Diffable Data Source 521 Pros and Cons of the Diffable Data Source 522 More Table View Editing 524 Rearranging Cells 524 Editable Content in Cells 525 Expandable Cell 527 Table View Swipe Action Buttons 528 Table View Menus 530 Table View Searching 531 Basic Configuration of a Search Controller 531 More Search Controller Configuration 533 Using a Search Controller 534 9. Collection Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 541 Collection View Classes 544 Flow Layout 546 Compositional Layout 550 Size, Count, Spacing, and Insets 550 Supplementary Items 554 Multiple Section Layouts 555 Other Compositional Layout Features 556 x | Table of Contents
Collection View Diffable Data Source 559 Diffable Data Source Construction 559 Registration Objects 562 Section Snapshots 564 Collection View Lists 565 Hierarchical Items 569 Basic Cell Manipulation 573 Selecting Cells 573 Deleting Cells 574 Menu Handling 575 Rearranging Cells 575 Custom Collection View Layouts 577 Tweaking a Layout 577 Collection View Layout Subclass 580 Decoration Views 582 Switching Layouts 583 Collection Views and UIKit Dynamics 584 10. iPad Interface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587 Popovers 587 Arrow Source and Direction 590 Popover Size 590 Popover Appearance 591 Passthrough Views 594 Popover Presentation, Dismissal, and Delegate 594 Adaptive Popovers 596 Popover Segues 597 Popover Presenting a View Controller 598 Split Views 599 Expanded Split View Controller 601 Collapsed Split View Controller 604 Collapsing and Expanding Split View Controller 606 Customizing a Split View Controller 609 Split View Controller Delegate Methods 612 Expanding a Split View Controller 613 View Controller Message Percolation 613 iPad Multitasking 615 Drag and Drop 618 Drag and Drop Architecture 618 Basic Drag and Drop 620 Item Providers 622 Slow Data Delivery 626 Table of Contents | xi
Additional Delegate Methods 627 Table Views and Collection Views 630 Spring Loading 635 iPhone and Local Drag and Drop 636 Pointer and Keyboard 637 Multiple Windows 640 The Window Architecture 641 Scene Creation 642 Window Creation and Closing 643 State Saving and Restoration 645 Further Multiple Window Considerations 647 11. Text. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 649 Fonts and Font Descriptors 650 Fonts 650 Symbol Images and Text 654 Font Descriptors 655 Choosing a Font 658 Adding Fonts 659 Attributed Strings 661 Attributed String Attributes 662 Making an Attributed String 665 Modifying and Querying an Attributed String 670 Custom Attributes 671 Drawing and Measuring an Attributed String 672 Labels 673 Number of Lines 674 Wrapping and Truncation 674 Fitting Label to Text 675 Customized Label Drawing 677 Text Fields 677 Summoning and Dismissing the Keyboard 680 Keyboard Covers Text Field 682 Text Field Delegate and Control Event Messages 686 Text Field Menu 689 Drag and Drop 691 Keyboard and Input Configuration 691 Text Views 698 Links, Text Attachments, and Data 699 Self-Sizing Text View 702 Text View and Keyboard 702 Text Kit 703 xii | Table of Contents
Text View and Text Kit 704 Text Container 705 Alternative Text Kit Stack Architectures 708 Layout Manager 709 Text Kit Without a Text View 713 12. Web Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 717 WKWebView 718 Web View Content 720 Tracking Changes in a Web View 721 Web View Navigation 722 Communicating with a Web Page 724 Custom Schemes 728 Web View Previews and Context Menus 730 Safari View Controller 731 Developing Web View Content 733 13. Controls and Other Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 735 UIActivityIndicatorView 735 UIProgressView 737 Progress View Alternatives 739 The Progress Class 739 UIPickerView 741 UIColorPickerViewController 743 UISearchBar 744 UIControl 748 Control States 748 Control Events 749 Control Actions 750 Control Menus 755 UISwitch 755 UIColorWell 756 UIStepper 756 UIPageControl 758 UIDatePicker 759 UISlider 762 UISegmentedControl 765 UIButton 768 Custom Controls 775 Bars 777 Bar Position 778 Bar Metrics 779 Table of Contents | xiii
Bar and Item Appearance 779 Bar Background and Shadow 781 Bar Button Items 782 Navigation Bar 786 Toolbar 788 Tab Bar 789 Tint Color 792 Appearance Proxy 793 14. Modal Dialogs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 797 Alerts and Action Sheets 797 Alerts 798 Action Sheets 801 Alert Alternatives 803 Quick Actions 803 Local Notifications 808 Authorization for Local Notifications 811 Notification Categories 815 Scheduling a Local Notification 818 Hearing About a Local Notification 820 Grouped Notifications 823 Managing Notifications 824 Notification Content Extensions 825 Activity Views 828 Presenting an Activity View 829 Custom Activities 832 Action Extensions 835 Share Extensions 838 Part III. Some Frameworks 15. Audio. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 845 System Sounds 845 Audio Session 847 Category 847 Activation and Deactivation 848 Ducking 849 Interruptions 850 Secondary Audio 851 Routing Changes 852 Audio Player 853 xiv | Table of Contents
Remote Control of Your Sound 856 Playing Sound in the Background 859 AVAudioRecorder 860 AVAudioEngine 861 MIDI Playback 867 Text to Speech 867 Speech to Text 868 Further Topics in Sound 871 16. Video. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 873 AVPlayerViewController 874 AVPlayerViewController Configuration 876 Picture-in-Picture 878 Introducing AV Foundation 880 Some AV Foundation Classes 880 Things Take Time 881 Time Is Measured Oddly 884 Constructing Media 885 AVPlayerLayer 891 Further Exploration of AV Foundation 893 UIVideoEditorController 894 17. Music Library. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 897 Music Library Authorization 897 Exploring the Music Library 899 Querying the Music Library 900 Persistence and Change in the Music Library 904 Music Player 904 Setting the Queue 905 Modifying the Queue 907 Player State 907 MPVolumeView 909 Playing Songs with AV Foundation 909 Media Picker 912 18. Photo Library and Camera. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 915 Browsing the Photo Library 915 PHPickerViewController Presentation 916 PHPickerViewController Delegate 916 Dealing with PHPickerViewController Results 917 Photos Framework 920 Querying the Photo Library 922 Table of Contents | xv
Modifying the Library 924 Being Notified of Changes 926 Fetching Images 927 Editing Images 932 Photo Editing Extension 937 Using the Camera 938 Capture with UIImagePickerController 939 Capture with AV Foundation 943 19. Contacts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 947 Contact Classes 947 Fetching Contact Information 949 Fetching a Contact 949 Repopulating a Contact 950 Labeled Values 951 Contact Formatters 951 Saving Contact Information 953 Contact Sorting, Groups, and Containers 953 Contacts Interface 954 CNContactPickerViewController 955 CNContactViewController 957 20. Calendar. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 961 Calendar Database Contents 962 Calendars 962 Calendar Items 963 Calendar Database Changes 963 Creating Calendars, Events, and Reminders 964 Events 964 Alarms 965 Recurrence 966 Reminders 967 Proximity Alarms 969 Fetching Events and Reminders 969 Calendar Interface 970 EKEventViewController 971 EKEventEditViewController 972 EKCalendarChooser 972 21. Maps. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 975 Map Views 975 Displaying a Region 976 xvi | Table of Contents
Scrolling and Zooming 977 Other Map View Customizations 979 Map Images 979 Annotations 980 Customizing an MKMarkerAnnotationView 981 Changing the Annotation View Class 983 Custom Annotation View Class 985 Custom Annotation Class 986 Annotation View Hiding and Clustering 987 Other Annotation Features 989 Overlays 991 Custom Overlay Class 992 Custom Overlay Renderer 994 Other Overlay Features 996 Map Kit and Current Location 997 Communicating with the Maps App 999 Geocoding, Searching, and Directions 1001 Geocoding 1001 Searching 1003 Directions 1004 22. Sensors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1007 Core Location 1008 Location Manager and Delegate 1009 Location Services Authorization 1009 Location Tracking 1014 Where Am I? 1018 Continuous Background Location 1019 Location Monitoring 1020 Heading 1024 Acceleration, Attitude, and Activity 1026 Shake Events 1026 Using Core Motion 1027 Raw Acceleration 1028 Gyroscope 1032 Other Core Motion Data 1038 Part IV. Final Topics 23. Persistent Storage. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1047 The Sandbox 1047 Table of Contents | xvii
Standard Directories 1047 Inspecting the Sandbox 1048 Basic File Operations 1049 Saving and Reading Files 1050 File Coordinators 1056 File Wrappers 1056 User Defaults 1057 Simple Sharing and Previewing of Files 1060 File Sharing 1060 Document Types and Receiving a Document 1060 Handing Over a Document 1063 Previewing a Document 1064 Quick Look Previews 1065 Document Architecture 1066 A Basic Document Example 1068 iCloud 1072 Document Browser 1075 Custom Thumbnails 1078 Custom Previews 1079 Document Picker 1080 XML 1082 JSON 1084 Coding Keys 1086 Custom Decoding 1087 SQLite 1089 Core Data 1090 PDFs 1097 Image Files 1098 24. Basic Networking. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1101 HTTP Requests 1101 Obtaining a Session 1101 Session Configuration 1102 Session Tasks 1104 Session Delegate 1106 HTTP Request with Task Completion Function 1108 HTTP Request with Session Delegate 1110 One Session, One Delegate 1112 Delegate Memory Management 1113 Session and Delegate Encapsulation 1114 Downloading Table View Data 1118 Background Session 1121 xviii | Table of Contents
Comments 0
Loading comments...
Reply to Comment
Edit Comment