Вы находитесь на странице: 1из 67

Beginning iPhone Development with

SwiftUI: Exploring the iOS SDK (7th


Edition) Wallace Wang
Visit to download the full and correct content document:
https://ebookmass.com/product/beginning-iphone-development-with-swiftui-exploring-
the-ios-sdk-7th-edition-wallace-wang/
Beginning iPhone
Development
with Swif tUI
Exploring the iOS SDK

Seventh Edition

Wallace Wang
Beginning iPhone
Development with SwiftUI
Exploring the iOS SDK
Seventh Edition

Wallace Wang
Beginning iPhone Development with SwiftUI: Exploring the iOS SDK
Wallace Wang
San Diego, CA, USA

ISBN-13 (pbk): 978-1-4842-9540-3 ISBN-13 (electronic): 978-1-4842-9541-0


https://doi.org/10.1007/978-1-4842-9541-0
Copyright © 2023 by Wallace Wang
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the
material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation,
broadcasting, reproduction on microfilms or in any other physical way, and transmission or information
storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now
known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with
every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an
editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the
trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not
identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to
proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication,
neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or
omissions that may be made. The publisher makes no warranty, express or implied, with respect to the
material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Miriam Haidara
Development Editor: James Markham
Coordinating Editor: Jessica Vakili
Distributed to the book trade worldwide by Springer Science+Business Media New York, 1 NY Plaza,
New York, NY 10004. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-sbm.com, or
visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member (owner) is
Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware
corporation.
For information on translations, please e-mail booktranslations@springernature.com; for reprint,
paperback, or audio rights, please e-mail bookpermissions@springernature.com.
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and
licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales
web page at http://www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is available to
readers on the Github repository: https://github.com/Apress/Beginning-iPhone-Development-with-
SwiftUI. For more detailed information, please visit http://www.apress.com/source-code.
Printed on acid-free paper
Table of Contents
About the Author����������������������������������������������������������������������������������������������������� xi

About the Technical Reviewer������������������������������������������������������������������������������� xiii

Chapter 1: Understanding iOS Programming������������������������������������������������������������ 1


Learning About Xcode������������������������������������������������������������������������������������������������������������������� 4
Switching Between iOS Devices������������������������������������������������������������������������������������������������� 11
Changing the iOS Device Emulation Appearance������������������������������������������������������������������������ 14
Selecting User Interface Objects������������������������������������������������������������������������������������������������� 17
Manipulating the Xcode Panes��������������������������������������������������������������������������������������������������� 17
Summary������������������������������������������������������������������������������������������������������������������������������������ 21

Chapter 2: Designing User Interfaces with SwiftUI������������������������������������������������ 23


Modifying the User Interface with the Inspector Pane���������������������������������������������������������������� 30
Summary������������������������������������������������������������������������������������������������������������������������������������ 38

Chapter 3: Placing Views on the User Interface����������������������������������������������������� 39


Using the Padding Modifier��������������������������������������������������������������������������������������������������������� 39
Defining Spacing Within a Stack������������������������������������������������������������������������������������������������� 42
Aligning Views Within a Stack����������������������������������������������������������������������������������������������������� 44
Using Spacers����������������������������������������������������������������������������������������������������������������������������� 46
Using the Offset and Position Modifiers�������������������������������������������������������������������������������������� 50
Summary������������������������������������������������������������������������������������������������������������������������������������ 56

iii
Table of Contents

Chapter 4: Working with Text��������������������������������������������������������������������������������� 57


Changing the Appearance of Text������������������������������������������������������������������������������������������������ 62
Using the Label View������������������������������������������������������������������������������������������������������������������� 71
Adding a Border Around a Text or Label View����������������������������������������������������������������������������� 75
Summary������������������������������������������������������������������������������������������������������������������������������������ 76

Chapter 5: Working with Images���������������������������������������������������������������������������� 77


Displaying Shapes����������������������������������������������������������������������������������������������������������������������� 77
Coloring a Shape������������������������������������������������������������������������������������������������������������������� 80
Coloring a Shape with Gradients������������������������������������������������������������������������������������������� 82
Displaying Images����������������������������������������������������������������������������������������������������������������������� 85
Clipping Images��������������������������������������������������������������������������������������������������������������������� 87
Adding Shadows to Images��������������������������������������������������������������������������������������������������� 88
Adding a Border Around Images�������������������������������������������������������������������������������������������� 89
Defining the Opacity of an Image������������������������������������������������������������������������������������������ 90
Summary������������������������������������������������������������������������������������������������������������������������������������ 92

Chapter 6: Responding to the User with Buttons and Segmented Controls����������� 93


Running Code in a Button����������������������������������������������������������������������������������������������������������� 96
Storing Code to Run in a User Interface View��������������������������������������������������������������������������� 102
Using a Segmented Control������������������������������������������������������������������������������������������������������ 106
Running Code from a Segmented Control��������������������������������������������������������������������������� 114
Summary���������������������������������������������������������������������������������������������������������������������������������� 120

Chapter 7: Retrieving Text from Text Fields and Text Editors������������������������������� 121
Using Text Fields����������������������������������������������������������������������������������������������������������������������� 121
Defining Expandable Text Fields������������������������������������������������������������������������������������������ 122
Changing the Text Field Style���������������������������������������������������������������������������������������������� 124
Creating Secure Text Fields������������������������������������������������������������������������������������������������� 125
Using Autocorrect and Text Content������������������������������������������������������������������������������������ 126
Defining Different Keyboards���������������������������������������������������������������������������������������������� 128

iv
Table of Contents

Dismissing the Virtual Keyboard������������������������������������������������������������������������������������������ 130


Using a Text Editor��������������������������������������������������������������������������������������������������������������� 132
Summary���������������������������������������������������������������������������������������������������������������������������������� 135

Chapter 8: Limiting Choices with Pickers������������������������������������������������������������ 137


Using a Picker��������������������������������������������������������������������������������������������������������������������������� 137
Displaying Options in a Picker��������������������������������������������������������������������������������������������� 142
Populating a Picker with an Enumeration��������������������������������������������������������������������������� 146
Using the Color Picker��������������������������������������������������������������������������������������������������������������� 149
Using the Date Picker���������������������������������������������������������������������������������������������������������������� 153
Choosing a Date Picker Style���������������������������������������������������������������������������������������������� 154
Displaying a Date and/or Time��������������������������������������������������������������������������������������������� 155
Restricting a Date Range����������������������������������������������������������������������������������������������������� 156
Formatting Dates����������������������������������������������������������������������������������������������������������������� 161
Creating a MultiDate Picker������������������������������������������������������������������������������������������������������ 164
Summary���������������������������������������������������������������������������������������������������������������������������������� 171

Chapter 9: Limiting Choices with Toggles, Steppers, and Sliders������������������������ 173


Using a Toggle��������������������������������������������������������������������������������������������������������������������������� 173
Using a Stepper������������������������������������������������������������������������������������������������������������������������� 176
Defining a Range in a Stepper��������������������������������������������������������������������������������������������� 178
Defining an Increment/Decrement Value in a Stepper�������������������������������������������������������� 179
Using Sliders����������������������������������������������������������������������������������������������������������������������������� 182
Changing the Color of a Slider��������������������������������������������������������������������������������������������� 183
Defining a Range for a Slider����������������������������������������������������������������������������������������������� 183
Defining a Step Increment for a Slider�������������������������������������������������������������������������������� 184
Displaying Minimum and Maximum Labels on a Slider������������������������������������������������������� 184
Summary���������������������������������������������������������������������������������������������������������������������������������� 186

Chapter 10: Providing Options with Links and Menus������������������������������������������ 187


Using Links������������������������������������������������������������������������������������������������������������������������������� 187
Using ShareLinks���������������������������������������������������������������������������������������������������������������������� 188
Customizing a ShareLink����������������������������������������������������������������������������������������������������� 191

v
Table of Contents

Using Menus����������������������������������������������������������������������������������������������������������������������������� 195


Formatting Titles on the Menu and Buttons������������������������������������������������������������������������ 199
Adding a Submenu�������������������������������������������������������������������������������������������������������������� 201
Summary���������������������������������������������������������������������������������������������������������������������������������� 204

Chapter 11: Touch Gestures���������������������������������������������������������������������������������� 205


Detecting Tap Gestures������������������������������������������������������������������������������������������������������������� 205
Detecting Spatial Tap Gestures������������������������������������������������������������������������������������������������� 207
Detecting Long Press Gestures������������������������������������������������������������������������������������������������� 211
Detecting Magnification Gestures��������������������������������������������������������������������������������������������� 214
Detecting Rotation Gestures����������������������������������������������������������������������������������������������������� 219
Detecting Drag Gestures����������������������������������������������������������������������������������������������������������� 223
Defining Priority and Simultaneous Gestures��������������������������������������������������������������������������� 227
Defining a High-Priority Gesture������������������������������������������������������������������������������������������ 230
Defining Simultaneous Gestures����������������������������������������������������������������������������������������� 233
Summary���������������������������������������������������������������������������������������������������������������������������������� 236

Chapter 12: Using Alerts, Action Sheets, and Contextual Menus������������������������� 239
Displaying an Alert/Action Sheet����������������������������������������������������������������������������������������������� 240
Displaying and Responding to Multiple Buttons������������������������������������������������������������������ 243
Making Alert/ActionSheet Buttons Responsive������������������������������������������������������������������� 248
Displaying TextFields in an Alert����������������������������������������������������������������������������������������������� 254
Using Contextual Menus����������������������������������������������������������������������������������������������������������� 258
Summary���������������������������������������������������������������������������������������������������������������������������������� 261

Chapter 13: Displaying Lists��������������������������������������������������������������������������������� 263


Displaying Array Data in a List�������������������������������������������������������������������������������������������������� 266
Displaying Arrays of Structures in a List����������������������������������������������������������������������������������� 268
Creating Groups in a List����������������������������������������������������������������������������������������������������������� 271
Adding Line Separators to a List����������������������������������������������������������������������������������������������� 277
Displaying Alternating Colors to a List�������������������������������������������������������������������������������������� 280
Adding Swipe Gestures to a List����������������������������������������������������������������������������������������������� 284

vi
Table of Contents

Deleting Items from a List��������������������������������������������������������������������������������������������������� 285


Moving Items in a List��������������������������������������������������������������������������������������������������������� 288
Creating Custom Swipe Actions for a List��������������������������������������������������������������������������� 292
Searching a List������������������������������������������������������������������������������������������������������������������������ 298
Summary���������������������������������������������������������������������������������������������������������������������������������� 303

Chapter 14: Using Forms and Group Boxes���������������������������������������������������������� 305


Creating a Simple Form������������������������������������������������������������������������������������������������������������ 306
Dividing a Form into Sections��������������������������������������������������������������������������������������������������� 310
Disabling Views in a Form��������������������������������������������������������������������������������������������������������� 314
Using Group Boxes�������������������������������������������������������������������������������������������������������������������� 317
Summary���������������������������������������������������������������������������������������������������������������������������������� 319

Chapter 15: Using Disclosure Groups, Scroll Views, and Outline Groups������������� 321
Using a Disclosure Group���������������������������������������������������������������������������������������������������������� 322
Using a Scroll View������������������������������������������������������������������������������������������������������������������� 325
Jumping to a Specific Location������������������������������������������������������������������������������������������� 328
Defining a Horizontal Scroll View���������������������������������������������������������������������������������������� 334
Using an Outline Group������������������������������������������������������������������������������������������������������������� 335
Summary���������������������������������������������������������������������������������������������������������������������������������� 340

Chapter 16: Creating Charts��������������������������������������������������������������������������������� 343


Creating a Bar Chart������������������������������������������������������������������������������������������������������������������ 345
Defining Charts with Loops and Arrays������������������������������������������������������������������������������� 348
Defining Colors for a Bar Chart�������������������������������������������������������������������������������������������� 352
Displaying an Average Value with the RuleMark����������������������������������������������������������������� 357
Creating a Stacked Bar Chart���������������������������������������������������������������������������������������������� 361
Creating a Line Chart���������������������������������������������������������������������������������������������������������������� 364
Creating Area Charts����������������������������������������������������������������������������������������������������������������� 368
Creating a Point Chart��������������������������������������������������������������������������������������������������������������� 370
Creating a Rectangle Chart������������������������������������������������������������������������������������������������������� 373
Summary���������������������������������������������������������������������������������������������������������������������������������� 376

vii
Table of Contents

Chapter 17: Using the Navigation Stack��������������������������������������������������������������� 379


Using a Navigation Stack���������������������������������������������������������������������������������������������������������� 380
Adding a Title to a Navigation Stack����������������������������������������������������������������������������������������� 384
Adding Buttons to a Navigation Stack��������������������������������������������������������������������������������������� 387
Displaying Views from a Navigation Stack�������������������������������������������������������������������������������� 394
Passing Data Between Structures in a Navigation Stack���������������������������������������������������� 399
Changing Data Between Structures in a Navigation Stack�������������������������������������������������� 404
Sharing Data Between Structures in a Navigation Stack���������������������������������������������������� 408
Using Lists in a Navigation Stack���������������������������������������������������������������������������������������������� 415
Summary���������������������������������������������������������������������������������������������������������������������������������� 420

Chapter 18: Using the Tab View���������������������������������������������������������������������������� 421


Using a Tab View����������������������������������������������������������������������������������������������������������������������� 422
Selecting Buttons Programmatically in a Tab Bar��������������������������������������������������������������������� 428
Displaying a Page View������������������������������������������������������������������������������������������������������������� 432
Displaying Structures in a Tab View������������������������������������������������������������������������������������������ 436
Passing Data Between Structures in a Tab View����������������������������������������������������������������� 440
Changing Data Between Structures in a Tab View��������������������������������������������������������������� 446
Sharing Data Between Structures in a Tab View����������������������������������������������������������������� 451
Summary���������������������������������������������������������������������������������������������������������������������������������� 457

Chapter 19: Using Grids���������������������������������������������������������������������������������������� 459


Defining Multiple Rows/Columns���������������������������������������������������������������������������������������������� 464
Adjusting Spacing Between Rows/Columns����������������������������������������������������������������������������� 467
Creating Tables Using GridRows����������������������������������������������������������������������������������������������� 471
Summary���������������������������������������������������������������������������������������������������������������������������������� 478

Chapter 20: Using Animation�������������������������������������������������������������������������������� 479


Moving Animation��������������������������������������������������������������������������������������������������������������������� 479
Scaling Animation��������������������������������������������������������������������������������������������������������������������� 484
Rotating Animation�������������������������������������������������������������������������������������������������������������������� 486
Animation Options��������������������������������������������������������������������������������������������������������������������� 488

viii
Table of Contents

Using Delays and Duration in Animation����������������������������������������������������������������������������� 491


Using an Interpolating Spring in Animation������������������������������������������������������������������������� 495
Using withAnimation����������������������������������������������������������������������������������������������������������������� 500
Summary���������������������������������������������������������������������������������������������������������������������������������� 505

Chapter 21: Using GeometryReader���������������������������������������������������������������������� 507


Understanding the GeometryReader����������������������������������������������������������������������������������������� 507
Understanding the Differences Between Global and Local Coordinates����������������������������������� 512
Identifying Minimum, Mid, and Maximum Values of a GeometryReader����������������������������������� 517
Summary���������������������������������������������������������������������������������������������������������������������������������� 520

Appendix: An Introduction to Swift���������������������������������������������������������������������� 521

Index��������������������������������������������������������������������������������������������������������������������� 577

ix
About the Author
Wallace Wang is a former Windows enthusiast who took one look at Vista and realized
that the future of computing belonged to the Mac. He's written more than 40 computer
books, including Microsoft Office for Dummies, Beginning Programming for Dummies,
Steal This Computer Book, Beginning ARKit for iPhone and iPad, and Pro iPhone
Development with SwiftUI. In addition to programming the Mac and iPhone/iPad, he
also performs stand-up comedy, having appeared on A&E’s An Evening at the Improv
and having performed in Las Vegas at the Riviera Comedy Club at the Riviera Hotel and
Casino. When he’s not writing computer books or performing stand-up comedy, he also
enjoys blogging about screenwriting at his site, https://15minutemoviemethod.com,
where he shares screenwriting tips with other aspiring screenwriters who all share the
goal of breaking into Hollywood.

xi
About the Technical Reviewer
Massimo Nardone has more than 22 years of experience
in security, web and mobile development, Cloud, and IT
architecture. His true IT passions are security and Android.
He has been programming and teaching how to program
with Android, Perl, PHP, Java, VB, Python, C/C++, and
MySQL for more than 20 years.
Massimo also holds a Master of Science degree in
computing science from the University of Salerno, Italy.
He has worked as a project manager, software engineer,
research engineer, chief security architect, information
security manager, PCI/SCADA auditor, and senior lead IT security/Cloud/SCADA
architect for many years.
His technical skills include security, Android, Cloud, Java, MySQL, Drupal, Cobol,
Perl, web and mobile development, MongoDB, D3, Joomla, Couchbase, C/C++, WebGL,
Python, Pro Rails, Django CMS, Jekyll, Scratch, etc.
He currently works as Chief Information Security Officer (CISO) for Cargotec Oyj.
He worked as a visiting lecturer and supervisor for exercises at the Networking
Laboratory of the Helsinki University of Technology (Aalto University). He holds four
international patents (PKI, SIP, SAML, and Proxy areas).

xiii
CHAPTER 1

Understanding
iOS Programming
Programming involves writing commands for a computer to follow. In iOS programming,
the computer is either an iPhone or an iPad. To create apps for an iPhone or iPad, you
need to learn three different skills:
• How to write commands in the Swift programming language

• How to use Apple’s software frameworks

• How to create user interfaces in Xcode

You need to write commands in the Swift programming language to make your app
do something unique. Then you rely on Apple’s software frameworks to handle common
tasks such as detecting touch gestures or accessing the camera. Finally, you design your
app’s user interface.
Apple’s software frameworks let you perform common tasks without writing (and
testing) your own Swift code. By relying on Apple’s proven and tested software frameworks,
you can focus solely on the unique features of your app rather than the mundane details of
making an app access different hardware features of an iPhone or iPad.
Ideally, you want your user interface to look good by adapting to all different screen
sizes such as an iPhone or iPad. The user interface lets you display information to the
user and retrieve information from the user. The best user interface is one that doesn’t
require even thinking about.
Essentially, every iOS app consists of three parts as shown in Figure 1-1:
• Your code to make an app do something useful

• A user interface that you can design visually in Xcode

• Access to hardware features of an iOS device through one or more of


Apple’s iOS frameworks
1
© Wallace Wang 2023
W. Wang, Beginning iPhone Development with SwiftUI, https://doi.org/10.1007/978-1-4842-9541-0_1
Chapter 1 Understanding iOS Programming

Figure 1-1. The three parts of an iOS app

Apple provides dozens of frameworks for iOS (and their other operating systems as
well such as macOS, watchOS, and tvOS). By simply using Apple’s frameworks, you can
accomplish common tasks by writing little code of your own. Some of Apple’s available
frameworks include

• SwiftUI – User interface and touch screen support

• ARKit – Augmented reality features

• Core Animation – Displays animation

• GameKit – Creates multiplayer interactive apps

• Contacts – Accesses the Contacts data on an iOS device

• SiriKit – Allows the use of voice commands through Siri

• AVKit – Allows playing of audio and video files

• Media Library – Allows access to images, audio, and video stored on


an iOS device
• CallKit – Provides voice calling features

Apple’s frameworks essentially contain code that you can reuse. This makes apps
more reliable and consistent while also saving developers’ time by using proven code that
works correctly. To see a complete list of Apple’s available software frameworks, visit the
Apple Developer Documentation site (https://developer.apple.com/documentation).
Apple’s frameworks can give you a huge head start in creating an iOS app, but you
still need to provide a user interface so users can interact with your app. While you could
create a user interface from scratch, this would also be tedious, time-consuming, and
error-prone. Even worse, if every app developer created a user interface from scratch, no
two iOS apps would look or work exactly the same, confusing users.

2
Chapter 1 Understanding iOS Programming

That’s why Apple’s Xcode compiler helps you design user interfaces with standard
features used in most apps such as buttons, labels, text fields, and sliders. In Xcode, each
window of a user interface is called a view. While simple iOS apps may consist of a single
view (think of the Calculator app on an iPhone), more sophisticated iOS apps consist of
multiple views.
To create user interfaces, Xcode offers two options:

• Storyboards

• SwiftUI

Storyboards let you design user interfaces visually by placing user interface objects
at specific locations on the screen as shown in Figure 1-2. Unfortunately, using fixed
values to define the position of various objects on a user interface means that storyboard
user interfaces do not adapt easily to different-size iOS device screens or orientations
(portrait or landscape).

Figure 1-2. Storyboards use fixed values to define the arrangement of objects on a
user interface

Since fixed values for arranging objects on a user interface won’t adapt to different
screen sizes, Apple offers a second way to design user interfaces using a framework
called SwiftUI. The main idea behind SwiftUI is that you place objects in the center of the
user interface and define their position relative to the center.

3
Chapter 1 Understanding iOS Programming

When the screen size is large, the distance between user interface objects expands.
When the screen size is small, the distance between user interface objects shrinks, so the
user interface adapts to the screen size automatically as shown in Figure 1-3.

Figure 1-3. SwiftUI user interfaces can adapt to different screen sizes
automatically

You can use storyboards and SwiftUI together in a single project, or you can use
either storyboards or SwiftUI by themselves. Because SwiftUI represents the future for
developing apps for all of Apple’s products, this book focuses exclusively on creating user
interfaces using SwiftUI rather than storyboards.

Learning About Xcode


Learning iOS development is more than just learning how to write code in the Swift
programming language. Besides knowing Swift, you must also know how to find and use
Apple’s different software frameworks, how to use Xcode to design your user interface
using SwiftUI, and how to organize, create, and delete files that contain your Swift code.
In addition, you must also learn how to write code using Xcode’s editor.

4
Chapter 1 Understanding iOS Programming

Each time you create an Xcode project, you’re actually creating a folder that contains
multiple files. A simple iOS app might consist of a handful of files, while a complicated
app might contain hundreds or even thousands of separate files.
By storing code in separate files, you can quickly identify the file that contains the
data you want to edit and modify while safely ignoring other files. No matter how many
files a project may hold, Xcode treats them as if all your Swift code were stored in a single
file. By breaking up your program into multiple files, you can group different parts of
your program in separate files to organize your app.
To further help you organize multiple files in a project, Xcode lets you create
separate folders. These folders exist solely for your convenience in organizing your code.
Figure 1-4 shows how Xcode can divide an app into folders and files.

Figure 1-4. Xcode stores your code in files that you can organize in folders

To get acquainted with iOS app development, let’s start with a simple project that
will teach you

• How to understand the parts of a project


• How to view different files

• How the different parts of Xcode work


1. Start Xcode. A welcoming screen appears that lets you choose a
recently used project or the option of creating a new project as
shown in Figure 1-5. (You can always open this welcoming screen
from within Xcode by choosing Windows ➤ Welcome to Xcode or
by pressing Shift + Command + 1.

5
Chapter 1 Understanding iOS Programming

Figure 1-5. The Xcode welcoming screen

2. Click the Create a new Xcode project option. Xcode displays


templates for designing different types of apps as shown in
Figure 1-6. Notice that the top of the template window displays
different operating systems you can develop apps for such as
iOS, watchOS, tvOS, and macOS. By selecting different operating
systems, you can create projects designed for the devices that run
that particular operating system.

6
Chapter 1 Understanding iOS Programming

Figure 1-6. Choosing a project template

3. Click iOS and then click App. The App template represents the
most basic iOS project.

4. Click the Next button. Another window appears, asking for your
project name along with an organization name and organization
identifier as shown in Figure 1-7. You must fill out all three text
fields, but the project name, organization name, and organization
identifier can be any descriptive text that you want. Notice that the
user interface popup menu lets you choose between SwiftUI and
Storyboard. For every project in this book, always make sure you
choose SwiftUI.

7
Chapter 1 Understanding iOS Programming

Figure 1-7. Defining a project name, organization name, and organization


identifier

5. Click in the Project Name text field and type a name for your
project such as MyFirstApp.

6. Click in the Team text field and type your name or company name.

7. Click in the Organization Identifier text field and type any


identifying text you wish. Typically this identifier is your website
spelled backward such as com.microsoft.

8. Click the Interface popup menu and choose SwiftUI. Make sure
that all checkboxes are clear. Then click the Next button. Xcode
displays a dialog for you to choose which drive and folder to store
your project in.

9. Choose a drive and folder and click the Create button. Xcode
displays your newly created project.

The Xcode window may initially look confusing, but you need to see that Xcode
groups information in several panes. The far-left pane is called the Navigator pane.
By clicking icons at the top of the Navigator pane, you can view different parts of your
project as shown in Figure 1-8.

8
Chapter 1 Understanding iOS Programming

Figure 1-8. The Navigator pane appears on the far left of the Xcode window

The main SwiftUI file is called ContentView, which contains Swift code that defines
the user interface of an app:

import SwiftUI

struct ContentView: View {


    var body: some View {
        VStack {
            Image(systemName: "globe")
                .imageScale(.large)
                .foregroundColor(.accentColor)
            Text("Hello, world!")
        }
        .padding()
    }
}

struct ContentView_Previews: PreviewProvider {


    static var previews: some View {
        ContentView()
    }
}

The import SwiftUI line lets your app use the SwiftUI framework for designing user
interfaces.

9
Chapter 1 Understanding iOS Programming

The ContentView: View structure displays a single view on the screen. SwiftUI can
only display one view at a time on the screen. When you create a SwiftUI iOS app, the
default view is a vertical stack (VStack) that contains an Image view and a Text view.
The Image view displays a globe icon, and the Text view displays “Hello, world!” on
the screen.
The ContentView_Previews: PreviewProvider structure actually displays the user
interface in the Canvas pane, which appears to the right of the Swift code as shown in
Figure 1-9.

Figure 1-9. The Editor pane and the Canvas pane

When the Editor pane and the Canvas pane appear side by side, any changes you
make to the Editor pane appear in the Canvas pane and vice versa. If you click the Editor
Options icon in the upper-right corner, you can hide or display the Canvas pane as
shown in Figure 1-10.

10
Chapter 1 Understanding iOS Programming

Figure 1-10. The Editor Options icon lets you toggle between displaying and
hiding the Canvas pane

The Canvas pane serves two purposes. First, it lets you see exactly what your user
interface looks like on a simulated iOS device. Besides letting you switch between
different simulated iOS devices (such as between different iPhone or iPad models),
the Canvas pane also lets you select different settings such as light or dark mode and
dynamic type. Changing iOS settings lets you see how your user interface might look
under different appearance options.

Switching Between iOS Devices


The Canvas pane emulates a single iOS device such as an iPhone 14 Pro or an iPad Mini.
That way you can see how your user interface adapts to the screen sizes of different iOS
devices. To make the Canvas pane emulate a different iOS device, follow these steps:

1. Click the name of the currently displayed iOS device at the top
of the Xcode window. A list of different iOS devices appears as
shown in Figure 1-11.

11
Chapter 1 Understanding iOS Programming

Figure 1-11. The list of iOS devices the Canvas pane can emulate

2. Click the iOS device you want to appear in the Canvas pane.
Xcode offers a second way to change the iOS device emulation in the Canvas pane by
using the Inspector pane. Follow these steps:

1. Move the cursor in ContentView() inside the ContentView_


Previews: PreviewProvider structure. The Inspector pane appears.

2. Click the Device popup menu and choose an iOS device to appear
in the Canvas pane as shown in Figure 1-12.

12
Chapter 1 Understanding iOS Programming

Figure 1-12. The Device popup menu can select iOS devices in the Inspector pane

After you choose a different iOS device for the Canvas pane, you can change the
magnification of the Canvas pane by clicking different icons that appear in the bottom-­
right corner of the Canvas pane as shown in Figure 1-13:

• Zoom Out – Shrinks the size of the iOS device

• Zoom to 100% – Displays the iOS device in its actual size (may cut off
parts of the iOS device, especially when emulating an iPad or larger
iPhone model)

• Zoom to Fit – Makes the entire iOS device visible


• Zoom In – Expands the size of the iOS device

Figure 1-13. The Zoom icons let you change the magnification of the Canvas pane

13
Chapter 1 Understanding iOS Programming

The Zoom to 100% lets you see your user interface on the actual size of the emulated
iOS device, while the Zoom to Fit lets you see the entire emulated iOS device as shown
in Figure 1-14. Then you can use the Zoom Out and Zoom In options to adjust the size of
the iOS device to your liking.

Figure 1-14. Comparing Zoom to 100% and Zoom to Fit

Changing the iOS Device Emulation Appearance


Once you’ve selected an iOS device to emulate in the Canvas pane, you can customize
three additional ways to change the appearance of your user interface:

• Color Scheme – Displays either light or dark mode

• Orientation – Displays either portrait or landscape mode

• Dynamic Type – Changes the size of text

14
Chapter 1 Understanding iOS Programming

To change the appearance of the iOS device emulation in the Canvas pane, follow
these steps:

1. Click the Device Settings icon near the bottom of the Canvas pane.
A popup window appears as shown in Figure 1-15.

Figure 1-15. The Device Settings window

2. Click the on/off switch to the right of the setting you want to
change such as Color Scheme or Orientation.

3. Click an option to change the iOS device appearance, or drag the


slider to change the size of text under the Dynamic Type option.

15
Chapter 1 Understanding iOS Programming

If you want to compare different options side by side, follow these steps:

1. Click the Variants icon at the bottom of the Canvas pane. A popup
menu appears as shown in Figure 1-16.

Figure 1-16. The Variants popup menu

2. Choose an option such as Color Scheme Variants or Dynamic


Type Variants. Xcode displays all the different options at once as
shown in Figure 1-17.

Figure 1-17. The Orientation Variants displayed

3. Click the Live icon to view the iOS device back in the Canvas pane
again as shown in Figure 1-18.

Figure 1-18. The Live icon

16
Chapter 1 Understanding iOS Programming

Selecting User Interface Objects


Once you’ve placed objects on the user interface, you can only select them by moving
the cursor in the Swift code for that object. If you would rather click objects on the user
interface using the mouse, you must click the Selectable icon near the bottom of the
Canvas pane as shown in Figure 1-19.

Figure 1-19. The Selectable icon

Once you click the Selectable icon and click an object on the user interface, blue
borders appear around that object. These blue borders let you see the size of that object.
This can be handy for seeing how large an object’s background appears if you add a
background color.
The Live icon (see Figure 1-18) lets you interact with your user interface to test your
app. The Selectable icon makes it easy to edit your user interface.

Manipulating the Xcode Panes


The four Xcode panes (Navigator, Editor, Canvas, and Inspector) serve different purposes.
The Navigator pane displays information about your project such as the names of all
the files that make up that project. The Editor pane is where you can write and edit Swift
code. The Canvas pane is where you can see and test the user interface defined by your
Swift code. The Inspector pane displays information about the currently selected object.

17
Chapter 1 Understanding iOS Programming

You can resize any of the panes by moving the mouse pointer over the pane border
and dragging the mouse left or right. If you want, you can toggle between hiding and
displaying the Navigator and the Inspector pane. That way you can see more of the
Editor and Canvas panes.
To hide/display the Navigator or Inspector pane, you have two options as shown in
Figure 1-20:

• Choose View ➤ Navigators/Inspectors ➤ Hide/Show Navigator/


Inspector.

• Click the Show/Hide Navigator/Inspector pane icons.

Figure 1-20. Hiding or showing the Navigator and Inspector panes

The Navigator pane lets you select options to display in the Editor pane. The
Inspector pane lets you select user interface items to choose different ways to modify
them as shown in Figure 1-21.

18
Chapter 1 Understanding iOS Programming

Figure 1-21. The Inspector pane lists different ways to modify a selected item

To see how the Inspector pane works, follow these steps:

1. Create a new iOS App project and then click the ContentView file
in the Navigator pane. The Editor pane displays the contents of the
ContentView file.

2. Move the cursor in the Text(“Hello, world!”) line.

3. Click the Attributes Inspector icon in the Inspector pane as shown


in Figure 1-22. The Inspector pane displays additional ways to
modify the currently selected item.

19
Chapter 1 Understanding iOS Programming

Figure 1-22. The Attributes Inspector icon lets you view additional ways to modify
an item in the Inspector pane

As you can see, Xcode’s panes show different information about a project. The
Navigator pane (on the far left) lets you see an overview of your project. Clicking specific
items in the Navigator pane displays that item in the Editor pane. The Inspector pane (on
the far right) shows additional information about something selected in the Editor pane.
The Canvas pane lets you preview the appearance of your user interface.
If you explore Xcode, you’ll see dozens of features, but it’s not necessary to
understand everything at once to start using Xcode. Just focus on using only those
features you need and feel free to ignore the rest until you need them.

20
Chapter 1 Understanding iOS Programming

Summary
Creating iOS apps involves more than just writing code. To help your app access
hardware features of different iOS devices, you can use Apple’s software frameworks
that provide access to the camera or to the address book of an iOS device. The most
important framework that all SwiftUI projects use is the SwiftUI framework. By
combining your code with Apple’s existing software frameworks, you can focus on
writing code to make your app work and use Apple’s software frameworks to help you
perform common functions found on most iOS devices.
Besides writing code, every iOS app also needs a user interface. To create user
interfaces, use SwiftUI. Since SwiftUI makes it easy to create user interfaces that adapt to
different devices, SwiftUI is fast becoming the preferred way to design user interfaces for
apps on all of Apple’s platforms (macOS, iOS, iPadOS, watchOS, and tvOS).
The main tool for creating iOS apps is Apple’s free Xcode program, which lets you
create projects, organize the separate files of a project, and view and edit the contents of
each file. Xcode lets you design, edit, and test your app all in a single program. Although
Xcode offers dozens of features, you only need to use a handful of them to start creating
iOS apps of your own.
Learning iOS programming involves learning how to write commands using the
Swift programming language, learning how to find and use Apple’s various software
frameworks, learning how to design user interfaces in SwiftUI, and learning how to use
Xcode. While this might seem like a lot, this book will take you through each step of
the way so you’ll feel comfortable using Xcode and creating your own iOS apps in the
near future.

21
CHAPTER 2

Designing User Interfaces


with SwiftUI
Every app needs a user interface. The basic idea behind SwiftUI is to create a user
interface using building blocks known as “views.” A view displays a single item on the
user interface such as text, an image, or a button as shown in Figure 2-1.

Figure 2-1. The parts of a SwiftUI user interface

One limitation of SwiftUI is that it can only display a single view on the screen at a
time. To get around this limitation, SwiftUI offers something called “stacks.” A stack is
considered a single view but lets you combine or stack up to ten additional views. By
creating a stack, you can display more than one view on the screen. Stacks can even hold
other stacks, essentially letting you display as many views as you want on a single screen.

23
© Wallace Wang 2023
W. Wang, Beginning iPhone Development with SwiftUI, https://doi.org/10.1007/978-1-4842-9541-0_2
Chapter 2 Designing User Interfaces with SwiftUI

There are three types of stacks as shown in Figure 2-2:

• VStack – Vertical stacks that arrange views above and below


another view

• HStack – Horizontal stacks that arrange views side by side

• ZStack – A stack that overlays views directly over each other

Figure 2-2. Vertical, horizontal, and ZStacks

A stack counts as a single view. By using horizontal (HStack) or vertical (VStack)


stacks, you can add up to ten (10) views inside a stack. For greater flexibility, you can
embed stacks inside of stacks to display as many views as necessary.

Note A stack can only contain a maximum of ten (10) views. If you try to store 11
or more views inside of a stack, Xcode will display an error message and refuse to
run your program.

When creating a user interface in SwiftUI, you have three options:

• Type Swift code in the Editor pane.


• Drag and drop a view (such as a button) into your Swift code in the
Editor pane.

• Drag and drop a view (such as a button) into the Canvas pane.

24
Chapter 2 Designing User Interfaces with SwiftUI

Typing Swift code in the Editor pane to design a user interface is the fastest and most
flexible method, but takes time and requires familiarity with different options. To make
typing Swift code to define user interface views easier, Xcode displays a popup menu
of options when it recognizes what you’re trying to type. By choosing an option and
pressing Return, you can create a user interface view quickly as shown in Figure 2-3.

Figure 2-3. As you type Swift code to define a user interface view, Xcode displays a
menu of options

If you’re not familiar with your options for designing a user interface, it’s easier to use
the Library window, which lists all possible user interface views you can use as shown in
Figure 2-4.

25
Chapter 2 Designing User Interfaces with SwiftUI

Figure 2-4. Clicking the Library icon opens the Library window

Once you open the Library window, you can either

• Drag and drop a user interface view from the Library window into the
Editor pane as shown in Figure 2-5.

• Click the Selectable icon and then drag and drop a user interface
view onto the simulated iOS device user interface in the Canvas pane
as shown in Figure 2-6.

26
Chapter 2 Designing User Interfaces with SwiftUI

Figure 2-5. Drag and drop a user interface view into the Editor pane

Figure 2-6. Drag and drop a user interface view into the Canvas pane

27
Chapter 2 Designing User Interfaces with SwiftUI

No matter how you change the user interface, Xcode keeps all changes synchronized
between the Editor pane and the Canvas pane. That means when you type Swift code in
the Editor pane, the Canvas pane shows your changes right away. When you drag and
drop a user interface view into the Canvas pane, Xcode automatically adds that Swift
code in the Editor pane right away.
The Canvas pane displays your user interface, but if you want to test your app, you
have two choices as shown in Figure 2-7:

• Click the Run button or choose Product ➤ Run to open the Simulator.

• Click the Live icon at the bottom of the Canvas pane.

Figure 2-7. The Run button and the Live Preview icon

To see how SwiftUI works to create a simple user interface that can respond to the
user, follow these steps:

1. Create a new iOS App project, make sure the interface is SwiftUI,
and give it a descriptive name (such as SwiftExample).

2. Click the ContentView file in the Navigator pane. The Editor pane
displays the contents of the ContentView file.

28
Chapter 2 Designing User Interfaces with SwiftUI

3. Choose Editor ➤ Canvas. (Skip this step if a check mark already


appears in front of the Canvas option.) This opens the canvas so
you can preview your user interface.

4. Delete the text “Hello, world!” in the Text command and type the
following so the ContentView structure looks like this:

struct ContentView: View {


    @State private var message = true
    var body: some View {
        VStack {
            Toggle(isOn: $message) {
                Text("Toggle message on/off")
            }

            if message {
                Text ("Here's a secret message!")
            }
        }
    }
}

The preceding Swift code displays a toggle switch on the screen,


but you won’t be able to see it work unless you run your app in the
Simulator (which mimics an iOS device such as an iPhone or iPad)
or test it by clicking the Live icon. In most cases, the Live icon offers a
faster way to view and test your user interface in the Canvas pane.

5. Click the Live icon to turn on Live Preview. As you click the toggle,
notice that the message appears and disappears as shown in Figure 2-8.

Figure 2-8. Live Preview lets you interact with the user interface in the
Canvas pane

6. Click the Live icon again to turn off Live Preview.

29
Chapter 2 Designing User Interfaces with SwiftUI

Repeat the preceding steps except click the Run button to open the Simulator.
Testing your app in either the Simulator or the Canvas pane is identical. The main
difference is that the Canvas pane is usually much faster to use.
Now let’s go over this project so you get a rough idea how it works. First, it declares
a special State variable called “message,” which is initially set to true. Next, the
ContentView structure defines a single view as a VStack. That means anything inside this
VStack will appear stacked on top of each other.
The first view inside the VStack is a Toggle, which uses a Text view to display the
following text to the left of the toggle: “Toggle message on/off”. When the Toggle is on,
the “message” State variable gets changed to hold a true value. When the Toggle is off,
the “message” State variable gets changed to store a false value.
Underneath the Toggle, an if statement appears. If the “message” State variable is
true, then it shows a Text view that displays “Here’s a secret message!” If the “message”
State variable is false, then the Text view does not appear at all.

 odifying the User Interface with


M
the Inspector Pane
Creating a user interface in SwiftUI typically involves two steps. First, you arrange how
you want the various user interface views to appear on the screen. Next, you need to
customize each user interface view by changing its size, color, or position.
To customize user interface views, you add modifiers. Xcode gives you two ways to
add modifiers:

• Type modifiers directly in the Editor pane.

• Click the view you want to modify (either in the Editor pane or after
clicking the Selectable icon and then clicking the view in the Canvas
pane). Then select a modifier from the Inspector pane as shown in
Figure 2-9.

30
Chapter 2 Designing User Interfaces with SwiftUI

Figure 2-9. The Inspector pane displays different ways to modify a user
interface view

Typing modifiers directly into the Editor pane requires knowing the names of the
modifiers you want to use. As you get more experienced, typing modifiers directly
into your Swift code will be fast. However, when you’re first getting started, you may
not know which modifiers are even available. That’s when you might prefer using the
Inspector pane.
First, select the user interface view you want to modify. You can do this by moving
the cursor into the Swift code that defines that user interface view or by clicking the
Selectable icon and then clicking a user interface view in the Canvas pane. When
you select a user interface view, the Inspector pane displays modifiers for that
particular view.
The Inspector pane displays the most commonly used modifiers such as letting you
choose the font, alignment, or color for text. By clicking the Add Modifier button near
the bottom of the Inspector pane, you can view a list of additional modifiers as shown in
Figure 2-10.

31
Chapter 2 Designing User Interfaces with SwiftUI

Figure 2-10. The Add Modifier button displays a list of additional modifiers
you can use

32
Chapter 2 Designing User Interfaces with SwiftUI

When you see a modifier you want to use from the Add Modifier list, click that
modifier. Xcode displays that modifier in the Inspector pane. If you no longer want to see
any modifiers you may have added to the Inspector pane, click the Delete button in the
upper-right corner of that modifier as shown in Figure 2-11.

Figure 2-11. A Delete button appears to remove modifiers you have added to the
Inspector pane

Keep in mind that the order that you apply modifiers can make a difference.
Consider the following Text view with two modifiers, a background and a padding:

                Text ("Here's a secret message!")


                    .background(Color.yellow)
                    .padding()

This adds a background color of yellow to the Text view and then adds padding
(space) around that Text view. Suppose you switched these modifiers around like this:

                Text ("Here's a secret message!")


                    .padding()
                    .background(Color.yellow)

This order adds padding (space) around the Text view first and then colors the
background. Because the background now includes the added space, the background
color fills the space around the Text view as well, as shown in Figure 2-12.

Figure 2-12. The order of modifiers can make a difference

33
Chapter 2 Designing User Interfaces with SwiftUI

No matter which method you use to add modifiers, Xcode keeps everything
synchronized. So if you type modifiers in the Editor pane, your changes automatically
appear in the Inspector pane. Likewise, if you choose a modifier in the Inspector pane,
Xcode automatically adds that modifier to your Swift code in the Editor pane.
To see how to change the appearance of a user interface item, follow these steps:

1. Make sure your SwiftExample project from the previous section


is loaded in Xcode. The ContentView file should contain a Toggle
and a Text view that appears underneath the Toggle.

2. Click the Selectable icon near the bottom of the Canvas pane.
This will let you select views by clicking them directly in the
Canvas pane.

3. Click the Toggle in the Canvas pane or move the cursor in the
Toggle in the Editor pane. Xcode displays the Inspector pane
on the right side of the Xcode window, which shows you the
modifiers you can choose to change the appearance of the Toggle.

4. Click the Text view in the Canvas pane that displays “Here’s a
secret message!” or move the cursor into the Text view in the
Editor pane. Notice that the Inspector pane displays modifiers to
change the appearance of the Text view.

5. Click the Font popup menu. A list of different font options appears
as shown in Figure 2-13.

34
Another random document with
no related content on Scribd:
which a sliding element containing a fulminate strikes. The sliding
block carries a small charge of black powder which is set off by the
fulminate, thus igniting the train which leads to the high explosive
charge detonator. Were this sliding block left free to slide back and
forth at all times it would be unsafe to transport the fuze, as it might
be set off by accident. There must be therefore some means of
holding it safely away from the anvil until it is desired to detonate the
charge. There are thus two conflicting conditions to be met: safety
during transportation and sensitiveness at the point of departure. It
may not be understood at first why sensitiveness at the point of
departure should be a condition to be met. Suffice it to say that all
fuzes are designed to arm at discharge or soon after leaving the
bore for they must be ready to act at any time after leaving the
muzzle. Were they to be safe during flight they might be so safe that
the remaining velocity would not be sufficient to set them off. All
fuzes are designed to arm as we say either during travel through the
bore or immediately after.

Methods of Arming.
Spring method.—Let us suppose that after our projectile has
started on its way the sliding block is free to move within a cavity at
the forward end of which is the anvil. If the projectile comes to a
sudden drop or even sudden reduction of velocity the block if
unrestrained will, according to the principle of inertia, keep on going
till something stops it. The something in this case is the anvil and the
fulminate cap is set off. But it is not so simple. For while the projectile
is in flight it is acted upon by the air resistance and slows down but
the block in the cavity of the head is not subjected to this resistance.
It therefore gains on the projectile or creeps forward in the cavity
unless restrained as it is by a spring. Now one more point and this
type of fuze is complete. We supposed that our block was free to
slide. For safety’s sake it is pinned to the cavity. Again we call upon
inertia to bread the pin so as to leave the block free to slide. The
strength of the pin is calculated so that the force of inertia of the
mass of the block is greater than the resistance of the safety pin and
when the projectile starts the pin breaks and the spring forces the
block to the rear of the cavity until the sudden stop of the projectile
permits the block to slide forward as explained. Such a fuze requires
a comparatively high initial velocity and is not adapted to howitzers
using low muzzle velocities.
There are three other methods in use to arm the fuze. They are
inertia of a sleeve; centrifugal force and powder pellet system,
that is, combustion of a grain of powder holding the sliding block
from the anvil by means of an arm resting against the unburned
powder grain. These are more sensitive than the type described.
In the first system, a sleeve fitting around the plunger carrying
the cap slides to the rear by inertia when the projectile starts and two
clips engage in notches on the plunger body making the sleeve and
plunger thereafter move as one body, they are thus held together by
a plunger spring which before arming held the plunger away from the
anvil. The safety spring held the sleeve and plunger away from the
anvil and after arming prevents forward creeping by the plunger and
sleeve now locked together. Upon striking, the plunger and sleeve
move forward as one body and the cap strikes the anvil.
In centrifugal systems the primer plunger is kept safely away
from the anvil by a lock which is kept in place by springs. When the
rotational velocity reaches a certain point the force of the springs is
overcome by the centrifugal force and the locks are thrown aside or
opened and the plunger is free to move forward on impact.
In the powder pellet system (the one largely used by the
Germans) there is a well or channel filled with compressed powder,
this is set off by a fulminate cap which is fired by inertia, a small
plunger-anvil striking the cap. When the powder is consumed it
leaves a channel into which an arm attached to the sliding block
carrying the igniting fulminate for the charge may slide, thus
permitting the block to slide forward to the anvil fixed in the forward
part of the cavity. It is held from creeping forward after the
compressed powder is burned by a safety spring, thus insuring
sufficiently hard an impact to set off the cap.
Heretofore in our service the fulminating cap has been fixed and
the plunger carried the anvil or as we call it the firing pin. Such is
now the system in our base detonating fuzes, and in our combination
fuze.
The new point detonating fuzes are patterned after the French and
are practically French fuzes.

Fuzes Classification.
Fuses are classified as:
(a) Percussion if it acts on impact, producing a low order of
explosion.
(b) Time when it acts in the air at a certain point of the trajectory.
(c) Combination if it is able to act in the air or upon impact.
(d) Detonating when it contains a fulminate which will bring about
detonation upon impact.
The detonator may be separate or incorporated in the fuse. For
the 75-mm gun and the 155-mm howitzer it forms a part of the fuze.
Many fuzes are armed on set-back. An exception to this is the long
detonating fuse, MK 111, which is armed by the unrolling of a brass
spiral holding together two half rings made of steel so fitted as to
prevent the anvil and the head of the fuse from getting close
together. The spiral unrolls when the rotational velocity of the
projectile reaches a certain speed, thus drawing away the two steel
rings and arming the fuse.
DETONATING FUZE—MARK-III.

DETONATING FUZE—MARK-V.

It is of great importance that the spiral spring be not unrolled


during transportation or storage. This is prevented by winding a tape
of tarred canvas around the spirals, the head being covered by a thin
band of tinfoil. Just before loading the projectile the head and tape
are removed by pulling the free end of the tape.
The following precautions concerning fuses must be rigidly
observed to prevent grave accidents:
1. All detonators and detonating point fuses must be fitted with a
felt washer underneath, thus insuring proper seating in the central
tube.
2. Never disassemble a fuse by unscrewing.
3. Any fuse, the parts of which have become accidentally
unscrewed, must be destroyed at once. If fired it may cause a
premature burst; if handled a grave accident may result.
4. Any fuse or projectile which has been fired is dangerous,
because it may then be able to detonate by a very slight shock. It is
forbidden to touch it.
5. Never remove the tin hood from the long fuse before having
screwed the fuse in the central tube.
6. After having removed the tin hood, be sure that the spiral is in
its proper position. Never use a long fuse without the spiral.
7. Be sure the men understand that this spiral must not be
removed. It has happened that men have removed this spiral,
thinking that it was a device similar to the safety ring in trench mortar
fuzes, MK VII E.
8. See that the ring of the long fuze which connects the powder
train to the fuze body cannot be unscrewed. If it can be unscrewed
the fuze should be sent back to the depot.
9. If it is necessary to remove a shell with a long fuze by means of
the rammer, be sure to have a special rammer cup in the shape of a
hollow cylinder of wood which will fit between the shell and the
rammer.
10. Time and combination fuzes cannot be made absolutely water-
tight; the cover must therefore not be removed until the projectile is
about to be loaded.

Fuse Tables.
Tables showing American and French fuses to be used by our
Field Artillery, with information concerning markings, color, time of
delay, size of fuse, etc.
DETONATING FUSES.
Size
Corresponding
Time of delay. Color. of Cannon.
to.
Fuse.
2- 3” gun for target
MK I White head. Short. Russian 3GT. practice
100 only.
2-
M II (non delay) 8”, 9.2”,
100
2-
MK II (non delay) White top. Short. 204-m/m.
100
5- Gun and
MK II (short delay) Black top. Short. Modified.
100 Howitzer.
15-
M II (long delay) Black head. Short. Russian.
100
75 G; 3.8”G and
H; 4.7 in. G
MK III
zero No color. Long. French IAL. and H; 6”H;
(Supersensitive)
155H; all
gas shells.
2- French 24/31
MK IV (non-delay) White top. Short. SR (99- Howitzer only.
100 15).
5- French 24/31
MK IV (short delay) Black top. Short. AR (99- Howitzer only.
100 15).
Black top
15- French 24/31
violet
MK IV (long delay) Short. SR (99- Howitzer only.
100 detonator
15).
socket.
2- French 24/31
All guns, but not
MK V (non-delay) White top. Short. SR (99-
100 Howitzers.
08).
MK V (short delay) 5- Black top. Short. French 24/31 All guns, but not
AR (99- Howitzers.
100 08).
Mark—VII (non 2-
White. Short 6” T. M.
delay) 100
Black top with
20- violet
Mark VII (long delay) Short 6” T. M.
100 detonator
socket

Letter “E” after mark VII indicates safety device.


Note:—All American point detonating fuses are stamped on head cap in letters
and figures, .125 in high, with name of use, amount of delay, initials of loader, lot
and number; thus: PDF. MIV, xx Delay, FA, Lot No. xx.

45-SECOND COMBINATION FUZE MARK I.


21 SECOND COMBINATION FUZE MODEL OF 1907 M.

COMBINATION FUSES.
Total time By what
Corresponding On what projectile Wt. of
Fuse. burning cannon
French Type. used. fuse.
Sec. fired.
21 s/comb. F. All 3” and
22/31M 1897, Com. Shrapnel.
A., 1907 21 75-mm 1¼ lbs.
24 sec. MKi.
M. guns
21 s/comb. 22/31M 1916, All 3” and
Com. Shrapnel.
F.A., 21 24 sec. 75-mm 1¼ lbs.
MKi.
1915 AA. guns
31 s/comb. F. 30/55M 1889,
31 Com. Shrapnel. 4.7” gun. 2 lbs.
A. 1915 40 sec.
45 s/comb. F.
Same as
A. 1907 45
above.
M.
30/55M 1889, Com. Shrapnel,
155 How.
40 sec. MKi.
30/55M 1913, C. S. Shell AA 4.7” gun
40 sec. MKiii AA. Anti-
AA. Shrapnel. aircraft.

ACTION OF AMERICAN AND FRENCH DETONATING FUSES.


Time zero 1/ 2/ 5/ 15/
100 100 100 100
No Black with
Color Red. White. Black.
color. violet socket.
MK ii
American MKii None being made. MK i MK ii (LD)
(SD)
MK ii MK ii
Detonating Fuse is considered MK iv (LD)
(ND) (SD)
MK iV MK V
unsafe
(ND) (SD)
MK iV MK V
safe
(ND) (SD)
Will be abandoned MK V
Fuses
by French (ND)
French
detonating iAL. 1 SR. AR. LR.
fuses

Notes on Ammunition Marking.


Marks on H. E. Shell. These are of two kinds.
(a) Stamped marks made with a steel punch on the body of the
projectile just above the rotating band. These refer to the
manufacture of the projectile.
(b) Painted marks or bands which are clearly visible. They refer to
the loading, to the weight of the projectile and to the special
purposes for which the projectile is to be used.
Painted marks referring to loading are found on the ogive.
H. E. shells are usually painted red.
Marks referring to weight are painted in black just above the
rotating band, as follows:
L.— very light.
+— light.
++— normal.
+++— heavy.
++++— very heavy.
A white cross above these marks means that a plate has been
welded on the base. These marks are also painted on the boxes.
Shells fitted with cartridge cases (fixed ammunition) are not
painted below the rotating bands.
Special Shell.
Incendiary shells.—These incendiary shells are filled with some
flame-producing liquid, alumino thermic charge or incendiary cylinder
composed of slow burning linstock and string strongly impregnated
with saltpeter.
Markings.—Green with red ogive.
All shells containing black powder are more or less incendiary.
Percussion shrapnel is incendiary.
75-mm Ammunition.
Star Shells.—For 155 howitzer. Upon bursting, they liberate eight
white stars fitted with silken parachutes. The stars are projected
backward through the base of the projectile at the point of burst. The
parachutes open, the stars descending very slowly, illuminating the
surrounding objects for about 45 sec. The best height of burst is
about 300 m.; the burst interval should not be over 300. These shells
are also incendiary. Markings: a blue star and an “E.”
Gas shells are either toxic or tear-producing.
(a) Toxic shells are numbered either 4 or 5. The liquids 4 and 5
volatize, immediately upon contact with the air. The gases are
quickly diffused and easily carried by the wind.
Effect.—Liquid 4 acts immediately and is felt instantly.
Liquid 5, on the contrary, works more slowly and its effects are
apparent only after several hours. Markings: Green with white bands,
and numbers 4 or 5 on the ogive.
(b) Tear shells.—These shells are numbered 11, 12 and 13. They
are filled with two liquids, either mixed or separated, one liquid being
tear producing, the other smoke producing. When the shell bursts, a
greater part of the liquid is volatilized, the remainder being projected
to the ground in small drops which volatize with variable speed.
Markings: Green with numbers 11, 12 or 13 on the ogive.
Tracer shell.—This shell is fitted with a time fuse which ignites the
inside charge, the flames of which pass through the holes in the
ogive thus tracing the trajectory. Tracer shells are used in fire for
adjustment on aircraft. They are also incendiary. Markings: White
with blue ogive. Letter “T” painted on body.

PRECAUTIONS IN SEPARATE LOADING


PROJECTILES.
All projectiles must be seated accurately and carefully in loading,
otherwise not only inaccurate fire will result but also premature
detonations may occur.
Rotating bands should be smoothed and lightly greased just
before loading. In transport and in storage the bands should be
protected by rope bands, straw tithes, etc., to prevent deformation.
CHAPTER XIII
CARE AND PRESERVATION.

OILS AND CLEANING MATERIAL, TOOLS AND


ACCESSORIES FOR ARTILLERY MATERIEL
WITH THEIR USE.
In order that all parts of the materiel may function easily, it is
necessary that all the working and bearing surfaces may be properly
cleaned and lubricated with the appropriate lubricant. Where such
surfaces are not directly accessible, oil holes are provided; these
holes should be kept free from grit and dirt. Except during oiling, they
should be kept fully closed by the means provided.
For use in service, for the cleaning and preservation of this
materiel, the ordnance department issues hydroline oil, lubricating
oil, clock oil, vaseline, sperm oil, coal oil, neat’s-foot oil and light
slushing oil. Each of these oils are suited for the particular purpose
for which it is issued, as stated below, and care should be taken that
it is not used for other purposes.
Hydroline oil.—Used in the recoil cylinders of the carriage and for
no other purpose. Never used as a lubricant. It is characterized by its
low freezing point and its non-corrosive action on metals.
Lubricating oil (Engine oil Number 1).—A light petroleum oil used
exclusively in all oil holes of the materiel, and in lubricating such
parts as wheels and axles, guns and cradle slides, cradle pintle and
socket elevating and traversing mechanisms, exterior of cylinders,
brake bearings, hinges, different surfaces of breechblocks, threads,
breech recess, et cetera.
Clock oil.—Used on the spindle and all gearings of the Battery
Commander’s telescope, bearings of the panoramic sight, range
quadrants and fuze setters. In all cases clock oil should be used only
when the instruments mentioned are disassembled for cleaning. It
should be applied by dropping from the end of the dropper attached
to the end of the cork. In case of emergency, use as a substitute
either sperm oil or Engine oil No. 1, in the order mentioned.
Vaseline (Petrolatum).—The heavy petroleum oil free from rosin.
Used on the worm gears and the worm racks of the panoramic sight,
the hand and bracket fuze setter, B. C. telescope, and on the
micrometer screw and bushing of the quadrant. The spare parts of
the breech mechanism should also be coated with vaseline and each
piece then wrapped in paper to prevent the oil from being rubbed off.
Sperm oil.—A lighter lubricant than the lubricating oils, and may
be used on the gears of sights, fuze setters, ranges, quadrants, parts
of revolvers, et cetera; lubricating oil may also be used on such
parts. It is also used as a temporary rust preventive. Its low viscosity
and light body make it unsuitable for this purpose for more than a
few days.
Coal oil.—Used for cleaning purposes. In the field it may be used
for lanterns. Coal oil for general illuminating purposes is furnished by
the quartermaster department.
Neat’s-foot Oil.—An animal oil used for softening and preserving
leather. Applied with a moistened cloth to the flesh side of moistened
leather.
Light slushing oil.—The heavy petroleum oil similar to cosmic.
Used as a rust preventive. Essentially a mineral oil containing a large
per cent of rosin. Prescribed for use in the protection and
preservation of all bright or unpainted of steel or iron on all parts of
the equipment when the materiel is to remain unused for an
appreciable length of time. Its use as a lubricant for mobile artillery is
forbidden. Before applying the slushing oil to any surface, the parts
should be thoroughly cleaned so as to be free from rust, coal oil,
lubricating oil, et cetera, as their presence will cause rusting under
the slushing oil. The slushing oil should then be applied in a thin,
uniform coat, since this is all that is necessary to give good
protection. Except in very cold weather it can be applied by using a
paint brush as when painting, in cold weather it should be applied by
stippling—that is, by holding the brush perpendicular to the surface
to be coated and then tapping the surface with the point of the brush.
It can be applied through the bore of the gun by a slush brush issued
for that purpose. In cold weather it should be warmed before used in
the bore of the gun. It may be readily removed by burlap or waste
dipped coal oil.
Borax.—Issued for use as a flux in welding.
Lavaline.—A metal polish issued interchangeable with Gibson’s
soap polish. Used on bits and collars.
Lye, powdered.—When dissolved in water, one pound to six
quarts with sufficient lime to give a consistence of paint, is used to
remove old and blistered paint.
Napthaline.—A moth preventive, effective only after eggs and
grubs already present have been removed. Used in the storage of
blankets, et cetera.
Polish, Gibson’s Soap.—A metal polish issued interchangeably
with lavaline. Used on bits and collars.
Paint, rubberine.—Used in connection with loading ammunition in
accordance with instructions regarding the same.
Primer, brown enamel.—A hard, quick drying enamel used for
painting parts of horse collars, draft springs, et cetera.
Sal Soda, Bicarbonate of Soda.—A saturated solution of soda
and water makes an alkaline solution that will not rust. The solution
must be saturated, that is, at least 20% or one-fourth pound of soda
(6 heaping spoonfuls to one cup of water). This solution is an
effective solvent of powder fouling and should always be used after
firing, whether metal fouling solution is to be used or not. It reduces
the labor of cleaning with oil alone by more than half. Used also in a
weaker solution (one-half pound to 8 quarts of water) in washing
surfaces to be painted and to remove dirt and grease.
Soap, H. & H.—A neutral naphtha soap used in washing blankets,
web and cloth equipment. Applied in the form of a solution (one cake
to 9 cups of hot water). If for any cause this soap is not obtainable, a
good laundry soap (ivory or equal) may be used, but in no case
should yellow soap containing a large percentage of alkali be used.
Soap, castile.—An alkaline soap used in cleaning leather
equipment. Applied on a moistened sponge.
Soap, saddle (Hollingshead).—A soap used as a dressing for
leather equipment. Applied with a thick lather on a moistened
sponge.
Swabbing solution, contains.—Ammonium persulphate, 60
grains or one half spoonful smoothed off. Ammonia 28%, 6 oz. or ⅜
of a pint or 12 spoonfuls. Water, 4 oz. or ¼ pint or 8 spoonfuls.
Dissolve the ammonium persulphate in the water and add the
ammonia. Keep in a tightly corked bottle. Pour out only what is
necessary at a time and keep the bottle corked.

TOOLS AND ACCESSORIES.


In the repair of all equipment, it is literally true that “a stitch in time
saves nine,” and that a timely repair will save the entire article.
Tool Kits will be kept complete and serviceable; edges of cold
chisels free from nicks; drifts and punches properly shaped
immediately after using; and files kept clean.
To prevent unscrewing, copper wire is used to lash nuts and other
threaded parts which are not secured by split pins.
Contents of Leather Pouch for Spare Parts (carried in Trail
Boxes of 3-inch Guns):—
For Breechblock—
50 Split pins
1 Block latch and spring
1 Firing pin and spring
1 Firing pin sleeve
2 Handy oilers, 5-16 inch
Hinge pin catch
1
1 Lever latch spring
1 Locking bolt, nut and pin
1 Locking bolt spring
2 Oil hole covers with screws
1 Pallet pin
1 Sear
2 Trigger shaft detent
For Hand Fuze Setter—
2 Corrector scale screws
1 Guide plate lock screw
2 Index bar screws
1 Index plunger and spring
2 Oil hole screws
1 Range index
3 Range ring screws
1 Stop pin screw
For Bracket Fuze Setter—
1 Corrector scale screw
3 Guide screws
4 Housing screws & split washers
1 Knob washer
1 Range worm crank & knob taper pin
1 Range worm crank handle
2 Range ring screws
3 Split pins (0.125)
1 Spring and spring cover with screw
2 Stop pins with rivets
For Cylinder—
1 Drain-plug, cylinder
1 Elevating & traversing lock spring
1 Filling plug (piston rod)
5 Rings Garlock packing, ¾ in

Special Wrenches, Spanners, other tools and accessories will be


used only for the purposes for which they are intended. This purpose
is usually stamped upon the tool.
In assembling or disassembling parts of the materiel, no part will
be struck directly with a hammer. If force is necessary, a piece of
wood or copper should be interposed between the hammer and the
part struck. All nuts are provided with split pins as keepers.
A pair of wire cutting pliers is provided for use in pulling split
pins, cutting wire lashings, etc. When a nut is assembled the split pin
should always be inserted and properly opened.
Axes, hatchets, picks, pick mattocks and shovels are carried
on the carriage for use in the field and will not be put to other uses.
The working edges will be kept bright and lightly oiled, the edges
being sharpened if intended for cutting, or smooth if intended for
digging. Deformed blades, edges or points should be straightened at
the anvil and forge or in a vise. Shovel points are straightened with a
hammer on a block of wood.
The side edges of shovel blades should not be used as a mattock,
as such treatment will deform the blade. In the field, split handles
should be wrapped with a cord until they can be replaced by new
handles.
Canvas Buckets are used for watering animals, for washing
carriages and equipment. Whenever possible, they should be dried
before folding and replacing in the holders on the carriages.
A rip or hole may be patched and made practically water-tight by a
coat of shellac.
Lanterns are used for illuminating purposes in the field only.
Paulins are used to cover the harness and guns when in the field
or in park. On the march they are carried on the carriages, being
folded to serve as seat cushions. Holes and tears should always be
properly sewed, stitched or darned as soon as practicable.
Picket Ropes are used in the field as drag ropes for the carriages
or as picket lines for the animals. The ropes must be in a serviceable
condition and free from knots. To keep them in a serviceable
condition, splicing may often be necessary.

CARE AND CLEANING OF THE DIFFERENT


PARTS OF THE CARRIAGES.
To disassemble and to clean the cylinder.—For cleaning, the
cylinder is dismounted and emptied and the cylinder head, counter
recoil buffer, and piston rod removed. The interior of the cylinder, the
piston, the counter recoil buffer and the stuffing box should then be
thoroughly cleaned by the use of cotton waste. The removal of the
packing is not necessary in cleaning. The cylinder bore should be
carefully inspected, and if any rust has formed it should be removed
with coal oil, using if necessary, fine emery cloth. The latter must be
used with great care to prevent any increase in the clearance
between the piston and the cylinder. If rubbing, burring, or scoring of
the parts is noted, the rough spots should be carefully smoothed
down by a skilled workman with a dead smooth file or with emery
cloth, and the cause of the roughness ascertained and removed.
Where unusual rubbing or scoring has occurred, the facts will be
reported to the Officer of the Ordnance Department charged with the
duty of keeping the battery in repair, for his information and action.
The exterior of the cylinder should be kept well oiled and free from
rust and dirt, and an inspection made at least once a month to
ascertain its condition. Where rust has formed it should be removed
with coal oil, and, if necessary, emery cloth. For shipment or storage,
or where the carriage is to stand without firing for extended periods,
the cylinder should be coated with the light slushing oil used for the
bore of guns.
To fill the recoil cylinder.—If the cylinder is not completely filled,
loss of stability will occur and higher stresses than normal will be
developed in the carriage. For this reason the cylinder should be
filled with the greatest care, a commissioned should, himself, verify
that the cylinder is full and that no air is left in it, exception of the void

Вам также может понравиться