Linux Lab
Linux Lab
Submitted To Submitted By
Prof. Shubha Dubey Name: - Ankit Gupta
Enrollment No.: 20ENG2INT0003
Sage university, Indore
IET (IT)
INDEX
S. No Name of the Experiment Date of Page no. Remark
Experiment
09 How to use stack views to easily layout your UI. 01/11/2022 31-32
1
Sage university, Indore
IET (IT)
EXPERIMENT NO. 1
Auto Layout dynamically calculates the size and position of all the views in your view hierarchy,
based on constraints placed on those views. For example, you can constrain a button so that it is
horizontally centered with an Image view and so that the button’s top edge always remains 8
points below the image’s bottom. If the image view’s size or position changes, the button’s
position automatically adjusts to match.
This constraint-based approach to design allows you to build user interfaces that dynamically
respond to both internal and external changes.
External Changes
External changes occur when the size or shape of your super view changes. With each change, you
must update the layout of your view hierarchy to best use the available space. Here are some
common sources of external change:
Internal Changes
Internal changes occur when the size of the views or controls in your user interface change.
Internationalization is the process of making your app able to adapt to different languages,
regions, and cultures. The layout of an internationalized app must take these differences into
account and appear correctly in all the languages and regions that the app supports.
2
Sage university, Indore
IET (IT)
Internationalization has three main effects on layout. First, when you translate your user
interface into a different language, the labels require a different amount of space. German, for
example, typically requires considerably more space than English. Japanese frequently requires
much less.
Second, the format used to represent dates and numbers can change from region to region, even
if the language does not change. Although these changes are typically more subtle than the
language changes, the user interface still needs to adapt to the slight variation in size.
Third, changing the language can affect not just the size of the text, but the organization of the
layout as well. Different languages use different layout directions. English, for example, uses a
left-to-right layout direction, and Arabic and Hebrew use a right-to-left layout direction. In
general, the order of the user interface elements should match the layout direction. If a button
is in the bottom-right corner of the view in English, it should be in the bottom left in Arabic.
Finally, if your iOS app supports dynamic type, the user can change the font size used in your
app. This can change both the height and the width of any textual elements in your user interface.
If the user changes the font size while your app is running, both the fonts and the layout must
adapt.
Auto Layout defines your user interface using a series of constraints. Constraints typically
represent a relationship between two views. Auto Layout then calculates the size and location of
each view based on these constraints. This produces layouts that dynamically respond to both
internal and external changes.
Once you decided to write your constraints in code you enter a world with a lot of possibilities.
Luckily enough, these type of constraints are no longer needed:
NSLayoutConstraint.constraints(withVisualFormat: "H:|-[icon(==postDate)]-20-[titleLabel(120@250)]
-20@750-[postDate(>=50)]-|", metrics: nil, views: views)
It’s an example constraint written in the Auto Layout Visual Format Language.
We’ll focus on using Layout Anchors as introduced in iOS 9. It’s a great API that, nowadays, allows
you to write constraints in code quite easily.
3
Sage university, Indore
IET (IT)
constraints.
After that, you start by creating an array of constraints. In this array, you define your set of
constraints:
let constraints = [
view.centerXAnchor.constraint(equalTo: superview.centerXAnchor),
view.centerYAnchor.constraint(equalTo: superview.centerYAnchor),
view.widthAnchor.constraint(equalToConstant: 100),
view.heightAnchor.constraint(equalTo: view.widthAnchor)
]
NSLayoutConstraint.activate(constraints)
This example shows the basics of writing constraints and should be both readable and
understandable. It creates a square and centers it in its superview. The last line is needed to
actually activate the constraints so they make your layout appear as expected.
Each UIView comes with a collection of anchor properties that allow you to set up relations
between views:
extension UIView {
Each Anchor it returns subclasses from NSLayoutAnchor which comes with a few common methods to
set relationships. These include equal to, greater than, and less than or equal to relationships. It’s
best to explore its documentation and get yourself familiar with the available APIs.
Order of constraints
4
Sage university, Indore
IET (IT)
Once you start writing your constraints its important to keep in mind the order of your
constraints if you start working with constants.
let constraints = [
innerSquare.topAnchor.constraint(equalTo: outerSquare.topAnchor),
innerSquare.leftAnchor.constraint(equalTo: outerSquare.leftAnchor, constant: 40),
outerSquare.bottomAnchor.constraint(equalTo: innerSquare.bottomAnchor),
outerSquare.rightAnchor.constraint(equalTo: innerSquare.rightAnchor, constant: 40)
]
NSLayoutConstraint.activate(constraints)
Results in the following image in which the outer square is blue and the inner square is red:
A simple Auto
5
Sage university, Indore
IET (IT)
EXPERIMENT NO. 2
Aim: - Understanding the tools and technologies used to create IOS Apps.
Apple has introduced a variety of advanced tools and technologies to make app development
easier for programmers on various platforms since its establishment.
These tools make it possible for app developers to build highly functional and user-friendly
iPhone apps that get approved and published in just a few days.
Best iOS App Development Tools 2022
1. Xcode
Apple has introduced Xcode, a tool for creating Swift applications for iOS devices. It is the first
choice for new developers to create applications for the Mac, iPad, iPhone, Apple Watch, and
Apple TV.
The Xcode development environment, used to create iOS applications, has a text editor, a
compiler, and a build system. Moreover, it is the perfect tool for developers to write, compile,
debug, and publish the app on App Store.
If you’re looking for a tool that reduces the amount of development time needed to create a
mobile app, creates consistency and speediness in the app development process, consider using
this.
Features
You can design and test a graphical interface without writing a line of code.
With iOS SDK, you can build, install & run apps and debug them in a Mac-based Simulator.
To find any information, you can look in the Help index for complete documentation.
2. AppCode
6
Sage university, Indore
IET (IT)
AppCode is an advanced tool built on the IntelliJ IDEA platform and launched by JetBrains. It
uses plug-ins to extend its functionality, or you can extend its functionality by writing your own
plug-ins.
The tool can be used with a number of programming languages, including Objective-C, Swift, C++,
and JavaScript and is popular among iOS developers.
The major benefit of using the AppCode tool is that it makes writing and analysing code easy.
The IDE and editor are geared toward catching different coding errors, which enables developers
to fix them in time. This code management task helps developers in saving more time.
Features
3. Transporter
The Transporter tool helps in uploading your content directly to Apple. Being a developer, it
becomes easy for you to send apps, music, TV shows and movies, or books on the various Apple
platforms.
The Transporter development tool allows you to upload your content directly to Apple. As a
developer, it is easy to send music, TV shows and movies, apps or books on the different Apple
platforms.
To distribute your content in the App Store, Apple Music, Apple Books, or iTunes Store, you will
need to set up an App Store Connect account, iTunes Connect account, or give us valid encoding
7
Sage university, Indore
IET (IT)
house credentials.
Features
Drag and drop the content you want to move into Transporter.
You can upload multiple files at once from your computer to streamline the delivery
process.
To check the status of your issues fixing, look for validation warnings and delivery logs.
Keep records of all past deliveries, including the date and time.
4. Simulator
iOS developers rely on a program called Simulator to test their apps before sending them off to
Apple for approval. The simulator is an XCode tool installed on your Mac that allows you to run
iPhone, iPad, Apple Watch, or Apple TV applications in a window. It’s great for quick testing of
your application.
A simulation environment combines a simulated device and the simulation software that further
comes with its own settings and files. Settings and files will be saved to each device that gets
tested, so there isn’t a great deal of back-and-forth between screens.
Features
Smoothly interact with apps on iOS, watchOS, and tvOS with pointer and keyboard support.
Helps to prototype and debug apps
This tool can help you with prototyping and debugging apps.
You can easily tweak the graphics of a mobile app.
Test your iOS app for bugs before submitting it to Apple for review
5. Fabric
8
Sage university, Indore
IET (IT)
Fabric is one of the best iOS app development tools available, allowing developers to create a
wide range of different applications in real-time.
This product comes with a wide variety of app development kits, which can be easily integrated
into the app development environment and make it easy to create high-performing apps.
Fabric makes it easier for iOS developers to add new features to their applications. Fabric is a
lightweight iOS app development tool that makes it easy for developers to automate the
deployment process for their applications.
Features
Manage all your SDKs with one tool, saving you the hassle of juggling multiple accounts.
Hassle-free testing of code snippets.
6. Jazzy
You can now create easy-to-read documentation for your Objective-C and Swift code using the
Jazzy tool, a command-line utility. It uses Source Kit and Clang AST representation of code in
order to generate accurate and stellar results.
Moreover, the addition of Objective C and Swift capabilities will help iOS app developers manage
essential attributes and understand the purpose of writing certain code.
The Dash documentation viewer is installed directly to the source code of websites and makes
possible a great deal of accuracy and efficiency for developers. An end result is a tool that is
much loved by developers because it works so well.
Features
9
Sage university, Indore
IET (IT)
7. Cocoa Pods
Cocoa Pods is a dependency manager that streamlines your integration of third-party libraries
into your XCode projects. It is used by over 83,000 active developers and has been integrated
into more than 3 million apps.
To use Cocoa Pods, you create a Pod file—a text file that describes how your app depends on
other libraries. Cocoa Pods then resolves dependencies and fetches source code for the libraries,
placing it in an XCode workspace so that it can be linked with your app to create an iOS app.
Features
Third-party code from sources other than the owner of a project, integrated into a
project and available for distribution.
Eliminates dependency conflicts between libraries.
The app makes it easy to incorporate third-party libraries.
8. Design Code
Design Code tool is used to provide educational videos related to iOS app development that aids
developers in improving their learning skill, thereby resulting in faster results.
The video content covers a range of topics and techniques related to iOS app design and coding,
with tutorials on using XCode, Sketch, and Framer.
As a complete knowledge-based platform, it lets developers build faster and highly efficient iOS
10
Sage university, Indore
IET (IT)
apps. If the programmers like any content, they can bookmark them as well for later practices.
Features
9. Applyzer
Applyzer is an iOS tool that helps programmers to monitor their apps’ positions in the Apple
Store. This easy-to-use tool allows you to create an account and integrate your app ID to track
your apps’ positions on iTunes.
The Editor tool enables content developers to search for keywords in the app’s content. This
includes the ability to view a list of all the keywords that have been used and their results.
So, Applyzer is not exactly a development tool but it holds a great place in eyes of app
developers, marketers, investors and publishers.
Features
EXPERIMENT NO. 3
Aim: - Practicing and establishing connections between controllers and views.
The Role of View Controllers
View controllers are the foundation of your app’s internal structure. Every app has at least one
view controller, and most apps have several. Each view controller manages a portion of your app’s
11
Sage university, Indore
IET (IT)
user interface as well as the interactions between that interface and the underlying data. View
controllers also facilitate transitions between different parts of your user interface.
Because they play such an important role in your app, view controllers are at the center of
almost everything you do. The UIViewController class defines the methods and properties for
managing your views, handling events, transitioning from one view controller to another, and
coordinating with other parts of your app. You subclass UIViewController (or one of its subclasses)
and add the custom code you need to implement your app’s behavior.
Content view controllers manage a discrete piece of your app’s content and are the main
type of view controller that you create.
Container view controllers collect information from other view controllers (known as child
view controllers) and present it in a way that facilitates navigation or presents the
content of those view controllers differently.
Most custom view controllers you create are content view controllers — that is, the view controller
owns all of its views and manages interactions with those views. Use content view controllers to
present your app’s custom content onscreen, and use your view controller object to manage the
transfer of data to and from your custom views.
12
Sage university, Indore
IET (IT)
Step 2: Now, on Second View Controller Scene set Identity in Storyboard ID section
13
Sage university, Indore
IET (IT)
Step 3: In this step we are establishing connection from first View Controller Scene to Second View
Controller Scene, by adding some lines of code in first View Controller Scene in which we had given
Identity of Second View Controller Scene.
14
Sage university, Indore
IET (IT)
15
Sage university, Indore
IET (IT)
EXPERIMENT NO. 4
MKMapView
An embeddable map interface, similar to the one that the Maps app provides.
Declaration(iOS)
Use this class as-is to display map information and to manipulate the map contents from your
app. The map view supports several display styles, including the MKStandardMapConfiguration
that provides rich 2D and 3D presentations, an MKHybridMapConfiguration that provides a hybrid
satellite map presentation, and MKImageryMapConfiguration that provides an imagery-based map
presentation. Each of these map configurations support customization properties that refine
specific elements of the map’s presentation.
You can center the map on specific coordinates, specify the size of the area you want to display,
and annotate the map with custom information. When you initialize a map view, you specify the
initial region for that map to display by setting the region property of the map. MapKit defines
a region by a center point and a horizontal and vertical distance, referred to as the span. The
span defines how much of the map is visible, and is also how you set the zoom level. For example,
specifying a large span results in the user seeing a wide geographical area at a low zoom level,
whereas specifying a small span results in a more narrow geographical area and a higher zoom
level.
16
Sage university, Indore
IET (IT)
In addition to setting the span programmatically, the MKMapView class supports many standard
interactions for changing the position and zoom level of the map. In particular, map views
support flick and pinch gestures for scrolling around the map and zooming in and out. The map
view enables support for these gestures by default. You can enable and disable them using the
isScrollEnabled and isZoomEnabled properties.
You can also use projected map coordinates instead of regions to specify some values. When you
project the curved surface of the globe onto a flat surface, you get a two-dimensional version of
a map where longitude lines appear to be parallel. To specify locations and distances, you use the
MKMapPoint, MKMapSize, and MKMapRect data types.
Don’t subclass the MKMapView class itself. You can get information about the map view’s behavior
by providing a delegate object. The map view calls the methods of your custom delegate to let it
know about changes in the map status and to coordinate the display of custom annotations. The
delegate object can be any object in your app as long as it conforms to the MKMapViewDelegate
protocol. For more information about implementing the delegate object, see MKMapViewDelegate.
In macOS 10.14 and later, you can apply a light or dark appearance to your maps by modifying the
appearance property of your map view (or one of its ancestor views). Even if you specify a
custom appearance, users can use the Maps app to force all maps to adopt a light appearance.
Use the map view’s effectiveAppearance property to determine the actual appearance of your
map. For information about how to set view appearances, see Choosing a Specific Appearance for
Your macOS App.
Use this class as-is to display map information and to manipulate the map contents from your
app. The map view supports several display styles, including the MKStandardMapConfiguration
that provides rich 2D and 3D presentations, an MKHybridMapConfiguration that provides a hybrid
satellite map presentation, and MKImageryMapConfiguration that provides an imagery-based map
presentation. Each of these map configurations support customization properties that refine
specific elements of the map’s presentation.
You can center the map on specific coordinates, specify the size of the area you want to display,
and annotate the map with custom information. When you initialize a map view, you specify the
initial region for that map to display by setting the region property of the map. Map Kit defines
a region by a center point and a horizontal and vertical distance, referred to as the span. The
span defines how much of the map is visible, and is also how you set the zoom level. For example,
specifying a large span results in the user seeing a wide geographical area at a low zoom level,
whereas specifying a small span results in a more narrow geographical area and a higher zoom
level.
In addition to setting the span programmatically, the MKMapView class supports many standard
interactions for changing the position and zoom level of the map. In particular, map views
support flick and pinch gestures for scrolling around the map and zooming in and out. The map
view enables support for these gestures by default. You can enable and disable them using the
isScrollEnabled and isZoomEnabled properties.
17
Sage university, Indore
IET (IT)
You can also use projected map coordinates instead of regions to specify some values. When you
project the curved surface of the globe onto a flat surface, you get a two-dimensional version of
a map where longitude lines appear to be parallel. To specify locations and distances, you use the
MKMapPoint, MKMapSize, and MKMapRect data types.
Don’t subclass the MKMapView class itself. You can get information about the map view’s behavior
by providing a delegate object. The map view calls the methods of your custom delegate to let it
know about changes in the map status and to coordinate the display of custom annotations. The
delegate object can be any object in your app as long as it conforms to the MKMapViewDelegate
protocol. For more information about implementing the delegate object, see MKMapViewDelegate.
In macOS 10.14 and later, you can apply a light or dark appearance to your maps by modifying the
appearance property of your map view (or one of its ancestor views). Even if you specify a
custom appearance, users can use the Maps app to force all maps to adopt a light appearance.
Use the map view’s effectiveAppearance property to determine the actual appearance of your
map.
The MKMapView class supports the ability to annotate the map with custom information. Because
a map may have large numbers of annotations, map views differentiate between the annotation
objects MapKit uses to manage the annotation data and the view objects for presenting that data
on the map.
An annotation object is any object that conforms to the MKAnnotation protocol. Typically, you
implement annotation objects using existing classes in your app’s data model. This allows you to
manipulate the annotation data directly, but still make it available to the map view. Each
annotation object contains information about the annotation’s location on the map, along with
descriptive information that the map can display in a callout.
An annotation view, which is an instance of the MKAnnotationView class, handles the presentation
of annotation objects on the screen. An annotation view is responsible for presenting the
annotation data in a way that makes sense. For example, the Maps app uses a marker icon to
denote specific points of interest on a map. The Map Kit framework offers the
MKMarkerAnnotationView class for similar annotations in your own apps. You can also create
annotation views that cover larger portions of the map.
Because the map view needs annotation views only when they’re onscreen, the MKMapView class
provides a mechanism for queueing annotation views that aren’t in use. The map view detaches
annotation views with a reuse identifier and queues them internally when they move offscreen.
This feature improves memory use by keeping only a small number of annotation views in memory
at once, and by recycling the views you do have. It also improves scrolling performance by
alleviating the need to create new views while the map is scrolling.
When configuring your map interface, be sure to add all of your annotation objects right away.
The map view uses the coordinate data in each annotation object to determine when the
18
Sage university, Indore
IET (IT)
corresponding annotation view needs to appear onscreen. When an annotation moves onscreen, the
map view asks its delegate to create a corresponding annotation view. If your app has different
types of annotations, it can define different annotation view classes to represent each type.
You can use overlays to layer content over a wide portion of the map. An overlay object is any
object that conforms to the MKOverlay protocol. An overlay object is a data object that contains
the points that specify the shape and size of the overlay and its location on the map. Overlays
can represent shapes like circles, rectangles, multisegment lines, and simple or complex polygons.
You can also define your own custom overlays to represent other shapes.
Overlay renderer objects, which are instances of the MKOverlayRenderer class, handle the
presentation of an overlay. The job of the renderer is to draw the overlay’s content onto the
screen when the map view requests it. For example, if you have a simple overlay that represents
a bus route, you can use a polyline renderer to draw the line segments that trace the route of
the bus. You can also define a custom renderer that draws both the bus route and icons at the
location of each bus stop. When specifying overlays, you can add them to specific levels of the
map, which tells the map view to render them above or below other types of map content.
When configuring your map interface, you can add overlay objects at any time. The map view uses
the data in each overlay object to determine when the corresponding overlay view needs to
appear onscreen. When an overlay moves onscreen, the map view asks its delegate to create a
corresponding overlay renderer.
In iOS16 and macOS 13, and later, you can configure the map view to allow people to interact with
a wide variety of points of interest (POIs) the map displays. These are instances of the
MKMapFeatureAnnotation class, and cover a wide variety of elements visible on the map,
including:
You can control which features a person can interact with by configuring one of the
MKMapConfiguration subclasses that defines the map’s presentation. Create an
MKMapConfiguration with a set of MKMapFeatureOptions that describe the categories of POIs the
map responds to. To further refine the specific kinds of points of interest the map display
presents, use an MKPointOfInterestFilter.
When a person interacts with a specific POI, the framework calls your delegate object with one of
the MKMapViewDelegate protocol methods, depending on whether the person selects or deselects
a specific POI. These methods give your app a chance to respond to the selection or deselection
of an element. Depending on the kind of element, you can decide whether you want to customize
the display characteristics in the case of a POI, or in the case of territories or geographic map
features, you can create custom interactions to display information.
19
Sage university, Indore
IET (IT)
iOS16 and macOS 13, and later, support the inclusion of a Look Around view within the map view.
Look Around allows people to explore the environment at street level. You request a Look Around
view by creating an MKLookAroundSceneRequest with either an MKMapItem or a
CLLocationCoordinate2D, and if there’s Look Around imagery available for the specified location,
the framework returns an MKLookAroundScene for you to display using an
MKLookAroundViewController.
EXPERIMENT NO. 5
20
Sage university, Indore
IET (IT)
Application frameworks are not a recently emerged idea. Some of the old application frameworks
that are still used today are the SmallTalk user interface framework, MacApp (for Macintosh),
and Struts (for Web-based Java applications).
Due to the desire to create GUIs in applications with less development effort, application
frameworks proved to be a good solution, by providing a standard framework with underlying pre-
defined code structure.
An application framework acts as a tool to supply the structure and templates for constructing
an application. By using object-oriented techniques while implementing the framework, pre-
existing classes can be used to build the applications easily.
EXPERIMENT NO. 6
21
Sage university, Indore
IET (IT)
URL: A value that identifies the location of a resource, such as an item on a remote server or the
path to a local file.
Declaration
struct URL
Overview
You can construct URLs and access their parts. For URLs that represent local files, you can also
manipulate properties of those files directly, such as changing the file’s last modification date.
Finally, you can pass URLs to other APIs to retrieve the contents of those URLs. For example,
you can use URLSession and its related classes to access the contents of remote resources.
URLs are the preferred way to refer to local files. Most objects that read data from or write
data to a file have methods that accept a URL instead of a pathname as the file reference. For
example, you can get the contents of a local file URL as String by calling
init(contentsOf:encoding:), or as a Data by calling init(contentsOf:options:).
As a convenience, you can use Swift’s async-await syntax to asynchronously access the contents of
a URL through the resourceBytes and lines properties. These properties use the shared
URLSession instance to load the resource.
Topics
init?(string: String)
Creates a URL instance from the provided string.
init?(string: String, relativeTo: URL?)
Creates a URL instance from the provided string, relative to another URL.
init(fileURLWithPath: String)
Creates a file URL that references the local file or directory at path.
init(fileURLWithPath: String, isDirectory: Bool)
Creates a file URL that references the local file or directory at path.
init(fileURLWithPath: String, relativeTo: URL?)
Creates a file URL that references the local file or directory at path, relative to a base URL.
init(fileURLWithPath: String, isDirectory: Bool, relativeTo: URL?)
Creates a file URL that references the local file or directory at path, relative to a base URL.
init(fileURLWithFileSystemRepresentation: UnsafePointer<Int8>, isDirectory: Bool, relativeTo:
URL?)
Creates a file URL that references the local file or directory for the file system representation
of the path.
init(fileReferenceLiteralResourceName: String)
Creates a URL from a playground file literal.
init?(FilePath)
22
Sage university, Indore
IET (IT)
Creates a file URL that references the local file or directory at the file path you specify.
Deprecated
init?(FilePath, isDirectory: Bool)
Creates a file URL that references the local file or directory at the file path you specify.
Deprecated
NSURL
An object representing the location of a resource that bridges to URL; use NSURL when you need
reference semantics or other Foundation-specific behavior.
iOS 2.0+ iPadOS 2.0+ macOS 10.0+ Mac Catalyst 13.0+ tvOS 9.0+ watchOS 2.0+
Declaration
Overview
You can use URL objects to construct URLs and access their parts. For URLs that represent local
files, you can also manipulate properties of those files directly, such as changing the file’s last
modification date. Finally, you can pass URL objects to other APIs to retrieve the contents of
those URLs. For example, you can use the URLSession, NSURLConnection, and NSURLDownload
classes to access the contents of remote resources, as described in URL Loading System.
URL objects are the preferred way to refer to local files. Most objects that read data from or
write data to a file have methods that accept an NSURL object instead of a pathname as the file
reference. For example, you can get the contents of a local file URL as an NSString object using
the init(contentsOf:encoding:) initializer, or as an NSData object using the init(contentsOf:options:)
initializer.
You can also use URLs for interapplication communication. In macOS, the NSWorkspace class
provides the open(_:) method to open a location specified by a URL. Similarly, in iOS, the
UIApplication class provides the open(_:options:completionHandler:) method.
Additionally, you can use URLs when working with pasteboards, as described in NSURL Additions
Reference (part of the AppKit framework).
The NSURL class is “toll-free bridged” with its Core Foundation counterpart, CFURL. See Toll-
Free Bridging for more information on toll-free bridging.
Important
The Swift overlay to the Foundation framework provides the URL structure, which bridges to the
NSURL class. For more information about value types, see Classes and Structures in The Swift
Programming Language (Swift 4.1) and Working with Cocoa Frameworks in Using Swift with Cocoa
and Objective-C (Swift 4.1).
23
Sage university, Indore
IET (IT)
Structure of a URL
An NSURL object is composed of two parts—a potentially nil base URL and a string that is
resolved relative to the base URL. An NSURL object is considered absolute if its string part is
fully resolved without a base; all other URLs are considered relative.
For example, when constructing an NSURL object, you might specify file:///path/to/user/ as the
base URL and folder/file.html as the string part, as follows:
A URL can be also be divided into pieces based on its structure. For example, the URL
https://johnny:[email protected]:443/script.ext;param=value?query=value#ref contains
the following URL components:
Component Value
scheme https
user johnny
password p4ssw0rd
host www.example.com
port 443
path /script.ext
pathExtension ext
pathComponents ["/", "script.ext"]
parameterString param=value
query query=value
fragment ref
The NSURL class provides properties that let you examine each of these components.
EXPERIMENT NO. 7
24
Sage university, Indore
IET (IT)
"role": "container",
"components": [
{
"role": "title",
"text": "A Photo",
},
{
"role": "photo",
"URL": "bundle://<filename>.<extension>",
}
]
}
In the example above, the container component has two child components. Notice that a container
has a property named components whose value is an array. Any components inside the container’s
components array are children of the container.
Containers: -
EXPERIMENT NO. 8
First, to demonstra, we will add conflicting constraints to the view which will result in one of
them breaking and spitting console warnings.
25
Sage university, Indore
IET (IT)
self.view.addSubview(sampleView)
self.view.addConstraints(
NSLayoutConstraint.constraints(withVisualFormat: "V:|[sampleView(100)]",
options: NSLayoutConstraint.FormatOptions(rawValue: 0),
metrics: nil,
views: views)
)
"H:|[sampleView(100)]|"
Which says,
In order to better debug, we have added accessibilityIdentifier to view and corresponding superview.
This will help us to easily spot views with breaking constraints. When we run this app, we get the
following debug log letting me know about broken constraints.
26
Sage university, Indore
IET (IT)
As it is clear from debug log, XCode will also tell which constraints are breaking as a result of
the ambiguous layout and also the accessibility Identifier associated with it.
(Note: That since we have added accessbilityIdentifier to views, they are immediately recognizable in
the debugger. This is a nice trick to apply for easier debug logs readability)
1. Go to Breakpoint navigator
2. Click on + icon at the bottom-left corner
3. Choose an option Symbolic Breakpoint
4. Enter UIViewAlertForUnsatisfiableConstraints under symbol option
5. Press enter
6. Restart the app
27
Sage university, Indore
IET (IT)
As expected, it will halt the program execution and present with the following assembly code
which you can further analyse and use to debug breaking constraints.
Now going back, let's take a look at debug log, we get the following addresses for respective
views
This is the easiest way to capture the view with breaking constraints. When XCode detects the
view with breaking constraints, it will print a message which looks something like this,
28
Sage university, Indore
IET (IT)
Looking at this log, you will know that the view Sample View is undergoing breaking constraints and
the address associated with it is 0x7fba00e07c20.
The next step we will do is to capture the view hierarchy and try to locate this view in this
hierarchy,
While XCode is displaying this view hierarchy in the left menu bar, filter this hierarchy by
entering the view address in the bottom filter menu and it will immediately highlight the view
with breaking constraints.
Once you locate this view, you can take the next steps to analyse why constraints are breaking
and what you can do to fix them.
29
Sage university, Indore
IET (IT)
If you want to directly highlight views with breaking constraints for visual inspection, you can
even alter their properties on runtime using memory addresses as follows,
In Xcode,
1. Go to Debug menu
2. Select Pause
The program will pause and then you can go to debug console and execute the following command,
e (void)[CATransaction flush]
30
Sage university, Indore
IET (IT)
Where,
Please note that sometimes after evaluating UIView subclass appearance from a command line like
this won't immediately update the UI. iOS usually waits until the next run loop or any user event
such as tap or swipe occurs on the app. You can force the render server to update the display UI
with the following command.
e (void)[CATransaction flush]
Even if you are unable to locate faulted view in the debugger, using this trick, you can grab an
address of a suspicious view and change its appearance to provide a visual cue on the screen
As you can see We have changed the background color of view for which constraints were breaking
and now it appears like this.
To summarize, in order to avoid breaking constraints scenario you can follow some of
the tips below
Look at individual constraints and check if you have added them correctly
Watch out for incomplete and ambiguous constraint rules
Use accessbilityIdentifier to uniquely identify views with breaking constraints in the debugger
- This will help you easily locate views with breaking constraints by just looking at the
debug log
Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to pause and catch errors
in the debugger
This is a generic mistake for any iOS developer - When you create a view and add a
constraint to it programmatically, make sure to turn the autoresizing mask off by using
[your_view].translatesAutoresizingMaskIntoConstraints = false. (When you add autolayout constraints
in the storyboard or xibs, Interface builder will automatically turn it off for you.)
EXPERIMENT NO. 9
31
Sage university, Indore
IET (IT)
Stack Views
The following recipes show how you can use stack views to create layouts of increasing complexity.
Stack views are a powerful tool for quickly and easily designing your user interfaces. Their
attributes allow a high degree of control over how they lay out their arranged views. You can
augment these settings with additional, custom constraints; however, this increases the layout’s
complexity.
To view the source code for these recipes, see the Auto Layout Cookbook project.
This recipe uses a single, vertical stack view to lay out a label, image view, and button.
In Interface Builder, start by dragging out a vertical stack view, and add the flowers label, image
view, and edit button. Then set up the constraints as shown.
32
Sage university, Indore
IET (IT)
Attributes
You must pin the stack view to the superview, but otherwise, the stack view manages the entire
layout without any other explicit constraints.
In this recipe, the stack view fills its superview, with a small, standard margin. The arranged
views are resized to fill the stack view’s bounds. Horizontally, each view is stretched to match the
stack view’s width. Vertically, the views are stretched based on their CHCR priorities. The image
view should always shrink and grow to fill the available space. Therefore, its vertical content
hugging and compression resistance priorities must be lower than the label and button’s default
priorities.
Finally, set the image view’s mode to Aspect Fit. This setting forces the image view to resize the
image so that it fits within the image view’s bounds, while maintaining the image’s aspect ratio.
This lets the stack view arbitrarily resize the image view without distorting the image.
EXPERIMENT NO. 10
33
Sage university, Indore
IET (IT)
Inheritance
A class can inherit methods, properties, and other characteristics from another class. When one
class inherits from another, the inheriting class is known as a subclass, and the class it inherits
from is known as its superclass. Inheritance is a fundamental behavior that differentiates classes
from other types in Swift.
Classes in Swift can call and access methods, properties, and subscripts belonging to their
superclass and can provide their own overriding versions of those methods, properties, and
subscripts to refine or modify their behavior. Swift helps to ensure your overrides are correct by
checking that the override definition has a matching superclass definition.
Classes can also add property observers to inherited properties in order to be notified when the
value of a property changes. Property observers can be added to any property, regardless of
whether it was originally defined as a stored or computed property.
Any class that doesn’t inherit from another class is known as a base class.
Note
Swift classes don’t inherit from a universal base class. Classes you define without specifying a
superclass automatically become base classes for you to build upon.
The example below defines a base class called Vehicle. This base class defines a stored property
called currentSpeed, with a default value of 0.0 (inferring a property type of Double). The
currentSpeed property’s value is used by a read-only computed String property called description
to create a description of the vehicle.
The Vehicle base class also defines a method called makeNoise. This method doesn’t actually do
anything for a base Vehicle instance, but will be customized by subclasses of Vehicle later on:
1. class Vehicle {
2. var currentSpeed = 0.0
3. var description: String {
4. return "traveling at \(currentSpeed) miles per hour"
5. }
6. func makeNoise() {
7. // do nothing - an arbitrary vehicle doesn't necessarily make a noise
8. }
9. }
You create a new instance of Vehicle with initializer syntax, which is written as a type name
followed by empty parentheses:
Having created a new Vehicle instance, you can access its description property to print a human-
34
Sage university, Indore
IET (IT)
1. print("Vehicle: \(someVehicle.description)")
2. // Vehicle: traveling at 0.0 miles per hour
The Vehicle class defines common characteristics for an arbitrary vehicle, but isn’t much use in
itself. To make it more useful, you need to refine it to describe more specific kinds of vehicles.
Subclassing is the act of basing a new class on an existing class. The subclass inherits
characteristics from the existing class, which you can then refine. You can also add new
characteristics to the subclass.
To indicate that a subclass has a superclass, write the subclass name before the superclass name,
separated by a colon:
The following example defines a subclass called Bicycle, with a superclass of Vehicle:
The new Bicycle class automatically gains all of the characteristics of Vehicle, such as its
currentSpeed and description properties and its makeNoise() method.
Override
If the same method is defined in both the superclass and the subclass, then the method of the
subclass class overrides the method of the superclass. This is known as overriding.
class Vehicle {
func displayInfo(){
...
}
}
// override method
override func displayInfo() {
...
}
35
Sage university, Indore
IET (IT)
Here, the displayInfo() method of the Car subclass overrides the same method of the Vehicle
superclass.
class Vehicle {
Output
Four Wheeler
In the above example, we are overriding the displayInfo() method of the superclass Vehicle inside
the subclass Car.
Here, we have used the override keyword to specify the overridden method.
Now, when we call the displayInfo() method using the object car1 of Car,
car1.displayInfo()
36
Sage university, Indore
IET (IT)
Working of method
overriding
This is because the displayInfo() method of the Car subclass overrides the same method of the
Vehicle superclass.
37