Shell scripting in macOS – Part 6: User interaction

This article is a continuation of the previous article. We will be taking the previous script and using it to build on the concepts we will learning in this article.

Why would we need to do this?

So far our scripts have run without any communication between the script and any user. In many situations this might be enough. Often times we would need to ask the user for some information before proceeding. This could be for confirmation before performing a certain task, or to customise the script actions as they are being performed.

Ways of interacting with the user

We have a few options to do this.

  • read utility
  • GUI pop via AppleScript

Let us look at the read utility first.

Reading from stdin

The read commands captures data entered via stdin. This is typically the terminal prompt from where the user enters the data. This captured value is read into a variable.

#!/bin/bash

read -p " What is your name?": NAME 

echo $NAME 

This is a simple example. The user is prompted (on stdout) to enter their name. The user types the name and it is stored in a variable. The contents of the variable are then echoed out to stdout again.

Of course, this assumes the user is manually running the script. Later in this article we will go over how we can automate such scripts with the help of ‘expect’ utility.

Reading from a file

Reading from a file is possible thanks to the read command as well as the loop operations we learnt earlier.

Asking question via GUI

The easiest thing to do would be to prompt the user for information via a GUI popup. This makes the experience a lot better. However, we will need something else for that. We will leverage AppleScript (which is a macOS specific scripting language) to show the popup. This will be invoked from the shell script using osascript.

I will be covering the basics of AppleScript in a later article.

First we will look at how to get the dialog to appear using AppleScript. This requires the use of AppleScript display dialog command.

display dialog "Would you like to provide names for the folders or use the defaults instead?" buttons {"Custom", "Default"} default button 2

This will simply show a popup to the user with a message and 2 buttons. We can customise it further:

display dialog "Would you like to provide names for the folders or use the defaults instead?" buttons {"Custom", "Default"} default button 2 with icon POSIX file "/System/Library/CoreServices/HelpViewer.app/Contents/Resources/AppIcon.icns"

This adds a custom icon. If we run this script the user would see something like:

Make sure that the path to the custom icon is what you would want it to be.

If we wanted to find out which button the user has selected then:

button returned of (display dialog "Would you like to provide names for the folders or use the defaults instead?" buttons {"Custom", "Default"} default button 2 with icon POSIX file "/System/Library/CoreServices/HelpViewer.app/Contents/Resources/AppIcon.icns")

The button returned of tells us which button was clicked. It also adds a nice title for the popup.

The really nice thing to do would be to somehow run this from terminal. To do that we will use the osascript command. This command needs the AppleScript command to be passed is as a statement.

osascript -e '<AppleScript statement>'

Let us add our command here.

osascript -e 'button returned of (display dialog "Would you like to provide names for the folders or use the defaults instead?" buttons {"Custom", "Default"} default button 2 with icon POSIX file "/System/Library/CoreServices/HelpViewer.app/Contents/Resources/AppIcon.icns")'

Finally to get this value into a script variable we will use command substitution.

userClicked=$(/usr/bin/osascript -e 'button returned of (display dialog "Would you like to provide names for the folders or use the defaults instead?" buttons {"Custom", "Default"} default button 2 with icon POSIX file "/System/Library/CoreServices/HelpViewer.app/Contents/Resources/AppIcon.icns")')

We can now echo the variable or use it in a condition check.

Example

Let us update our code to ask the user for names they would like to give for their folder.

  1. Just after the line where we finish checking the 3 positional parameters, add this line.
#4. We can prompt the user to see if they wish to provide folder names themselves. This will override any values provided as arguments.
userClicked=$(/usr/bin/osascript -e 'button returned of (display dialog "Would you like to provide names for the folders or use the defaults instead?" buttons {"Custom", "Default"} default button 2 with icon POSIX file "/System/Library/CoreServices/HelpViewer.app/Contents/Resources/AppIcon.icns")')

This will first ask the user if they wish to provide the folder names or use the defaults. The response is captured in the shell variable userClicked.

  1. Below that we will put an if check to see what the user has selected.
# if the user decides to provide custom names then go ahead and ask the user via GUI prompts. Otherwise use the values sent as arguments or defaults.	
if [[ $userClicked == "Custom" ]]; then
	
else

fi
  1. If the condition is true we have to show dialog prompts to ask the user for the name. This is going to be similar to our first check. However, this one will also have the ability for the user to enter a value. Add 3 prompts, one for each folder. Also add an echo statement to write to the log file. The if should now look like:
if [[ $userClicked == "Custom" ]]; then
	echo "$(date) The user decided to provide custom names." >> $PATH_TO_LOG
	
	TOOLS_FOLDER=$(/usr/bin/osascript -e 'text returned of (display dialog "Enter the name of folder 1" default answer "Utilities" buttons {"OK"} default button 1 with title "Folder that will hold the utilities" with icon POSIX file "/Users/Shared/Finder.icns")')
	
	REPORTS_FOLDER=$(/usr/bin/osascript -e 'text returned of (display dialog "Enter the name of folder 2" default answer "Tools" buttons {"OK"} default button 1 with title "Folder that will hold the tools" with icon POSIX file "/Users/Shared/Finder.icns")')
	
	HELP_FOLDER=$(/usr/bin/osascript -e 'text returned of (display dialog "Enter the name of folder 3" default answer "Help" buttons {"OK"} default button 1 with title "Folder that will hold the support documents" with icon POSIX file "/Users/Shared/Finder.icns")')
		
	echo "$(date) User provided: $TOOLS_FOLDER $REPORTS_FOLDER $HELP_FOLDER" >> $PATH_TO_LOG
else
	echo "$(date) User decided to use default values: $TOOLS_FOLDER $REPORTS_FOLDER $HELP_FOLDER" >> $PATH_TO_LOG
fi

The script is now ready to accept user input. The completed script should look like:

#!/bin/zsh

#-------------------------------------------------------------------------------------------------
#NAME:		Folder creator
#AUTHOR:	Arun Patwardhan
#CONTACT:	arun@amaranthine.co.in
#DATE:		10th August 2021
#WEBSITE:	https://github.com/AmaranthineTech/ShellScripts
#-------------------------------------------------------------------------------------------------

#LEGAL DISCLAIMER --------------------------------------------------------------------------------
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
#SOFTWARE.
#-------------------------------------------------------------------------------------------------

#LICENSE/TERMS AND CONDITIONS --------------------------------------------------------------------
#MIT License

#Copyright (c) Amaranthine 2021.

#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#copies of the Software, and to permit persons to whom the Software is
#furnished to do so, subject to the following conditions:

#The above copyright notice and this permission notice shall be included in all
#copies or substantial portions of the Software.
#-------------------------------------------------------------------------------------------------

#ABOUT -------------------------------------------------------------------------------------------
# fileCreator.zsh
# 1.5
#-------------------------------------------------------------------------------------------------

#DESCRIPTION ------------------------------------------------------------------------------------- 
# - THis script is intended for creating the custom folders that are required on all corporate computers. 
# - Run this script on a new computer or a computer being reassigned to another employee.
# - This script can run on all computers.
#-------------------------------------------------------------------------------------------------

#USAGE -------------------------------------------------------------------------------------------
# - To create folders with default names run the command: ./folderCreator.zsh
# - To define your own folder names: ./folderCreator.zsh <folder1> <folder2> <folder3>
# - Available options  : Only the help option is available
# - Getting help       : Use the -h or the -help options to get more information. Or you can use the man command to view the man page.
#-------------------------------------------------------------------------------------------------

#WARNING/CAUTION ---------------------------------------------------------------------------------
#******************************************************************************************************************
#******************************************************************************************************************
#******************************************************************************************************************
#******************************************************************************************************************
# This script doesn't perform any validation of the folder names being passed in by the user. 
# If the script does not see the -h or the -help options then it will assume that the data being passed in is the name of the folder.
# The user of the script must ensure that the desired folder names are passed in.
#******************************************************************************************************************
#******************************************************************************************************************
#******************************************************************************************************************
#******************************************************************************************************************
#-------------------------------------------------------------------------------------------------

#INSTALLATION ------------------------------------------------------------------------------------
# Instructions for placing the script in the correct place are listed here. 
# Location:		/Library/Scripts/
# Permissions:	rwx r-x r-x
#-------------------------------------------------------------------------------------------------

#REQUIREMENTS ------------------------------------------------------------------------------------
# Shell:		/bin/zsh
# OS:			macOS Big Sur 11.4 or later
# Dependencies:	None
#-------------------------------------------------------------------------------------------------

#HELP/SUPPORT ------------------------------------------------------------------------------------
# You can get help by running the following commands.
# ./folderCreator.zsh -h
# ./folderCreator.zsh -help
# OR
# man folderCreator.zsh
# You can also view the log file for the same at: ~/Library/Logs/folderCreator_log_v1-5.log
#-------------------------------------------------------------------------------------------------

#HISTORY -----------------------------------------------------------------------------------------
# ------------------------------------------------------------------------------------------------
# Version 1.0: Basic script which creates the folders
# Version 1.1: Gives user the ability to specify the folder names at run time.
# Version 1.2: Adds safety checks to the scripts
# Version 1.3: Includes documentation as well as ability to get help.
# Version 1.4: Includes optimisation using for loop
# Version 1.5: Prompts the user in the GUI for names for the different folders.
#-------------------------------------------------------------------------------------------------

#-------------------------------------------------------------------------------------------------
# ------------------------------ SCRIPT STARTS HERE ----------------------------------------------
#-------------------------------------------------------------------------------------------------
#-------------------------------------------------------------------------------------------------
#-------------------------------------------------------------------------------------------------

#These are the default values used for the folder names incase the user doesn't provide any.
TOOLS_FOLDER="Tools"
REPORTS_FOLDER="Reports"
HELP_FOLDER="Help"

#Script version number
VERSION_NUMBER="1.5"

#Command name
COMMAND_NAME="folderCreator.zsh"

#1. Check to see if the user is asking for help. In which case we will have to provide information about the command.
if [[ $1 == "-h" ]] || [[ $1 == "-help" ]]; then
	echo "ABOUT 
-----
fileCreator_v1-5.zsh
Version $VERSION_NUMBER

NAME 
----
$COMMAND_NAME — Folder creation utility SYNOPSIS
$COMMAND_NAME folder names [ verbs ]

DESCRIPTION 
-----------
$COMMAND_NAME creates 3 folders in the home folder. In case the folder names are not provided then the command will create folders with default names 'Tools', 'Reports', \"Help\".

There is also the option of getting help via the help verb.
- This script is intended for creating the custom folders that are required on all corporate computers. 
- Run this script on a new computer or a computer being reassigned to another employee.
- This script can run on all computers.

VERBS 
-----
[ −h −help] Both the options are used to invoke the help documentation.
[ −v −version] Both the options are used to get the version number of the folderCreator command.

REQUIREMENTS 
------------
The following are the minimum requirements to get the script running.
Shell:\t\t zsh
OS:\t\t macOS Big Sur 11.4 or later
Dependencies:\t None

INSTALLATION 
------------
$COMMAND_NAME can be installed anywhere you wish. However, there are certain locations that are recommended.
Location:\t /Library/Scripts/ 
Permissions: \t rwxr-xr-x

USAGE  
-----
$COMMAND_NAME folder1 folder2 folder3 
Will create folders with your own names. 

$COMMAND_NAME -h OR $COMMAND_NAME -help 
Will invoke the help utility.

$COMMAND_NAME -v OR $COMMAND_NAME -version 
will print the version number in stdout.

WARNING/CAUTION  
---------------
$COMMAND_NAME does not perform any validation of names. The only options that folderCreator accepts are -h and -help verbs or the -v and 
-version verbs. If the script does not see the -h , -help or the -v , -version options then it will assume that the data being passed in is 
the name of the folder. The user of the folderCreator command must ensure that the desired folder names are passed in. The user will also be 
prompted, via the graphical user interface, if he/she wishes to provide the names for the folders. If yes, then there will be subsequent 
prompts asking for the folder names.

EXAMPLES 
--------
$COMMAND_NAME Resources Results Assistant
This will create 3 folders Resources , Results , Assistant , in the user’s home folder. 

$COMMAND_NAME
This will create 3 folders with the default names

$COMMAND_NAME Apps
This will use the Apps name for the first folder but the default names for the last 2 folders. 

NOTE
----
The user will be asked if he/she wishes to provide custom names in all the examples mentioned above. The user's value will always override 
whatever is being provided to the script or defaults.

DIAGNOSTICS 
-----------
The script produces a log file called ~/Library/Logs/folderCreator_log_v1-x.log
This file is typically located in the user’s home folder log folder. The x represents the version number of $COMMAND_NAME
You can view the logs for each respective version.

COPYRIGHT  
---------
Copyright (c) Amaranthine 2015-2021. All rights reserved. https://amaranthine.in

EXIT STATUS  
-----------
In most situations, $COMMAND_NAME exits 0 on success"
	exit 0
fi

echo "$(date) Running script $0 to create folders."
echo ""

TODAY=$(date)
PATH_TO_LOG="$HOME/Library/Logs/folderCreator_log_v1-5.log"

echo "$(date) Starting" >> $PATH_TO_LOG

#2. Check to see if the version number is 
if [[ $1 == "-version" ]] || [[ $1 == "-v" ]]; then
	echo "Version: $VERSION_NUMBER"
	exit 0
fi

#3. The following if statements check to see if the script is receiving any arguments. It then picks those arguments and assigns them to the respective variables for use in the script.
if [[ $1 != "" ]]; then
	TOOLS_FOLDER=$1
fi

if [[ $2 != "" ]]; then
	REPORTS_FOLDER=$2
fi

if [[ $3 != "" ]]; then
	HELP_FOLDER=$3
fi

#4. We can prompt the user to see if they wish to provide folder names themselves. This will override any values provided as arguments.
userClicked=$(/usr/bin/osascript -e 'button returned of (display dialog "Would you like to provide names for the folders or use the defaults instead?" buttons {"Custom", "Default"} default button 2 with icon POSIX file "/System/Library/CoreServices/HelpViewer.app/Contents/Resources/AppIcon.icns")')
	
# if the user decides to provide custom names then go ahead and ask the user via GUI prompts. Otherwise use the values sent as arguments or defaults.	
if [[ $userClicked == "Custom" ]]; then
	echo "$(date) The user decided to provide custom names." >> $PATH_TO_LOG
	
	TOOLS_FOLDER=$(/usr/bin/osascript -e 'text returned of (display dialog "Enter the name of folder 1" default answer "Utilities" buttons {"OK"} default button 1 with title "Folder that will hold the utilities" with icon POSIX file "/Users/Shared/Finder.icns")')
	
	REPORTS_FOLDER=$(/usr/bin/osascript -e 'text returned of (display dialog "Enter the name of folder 2" default answer "Tools" buttons {"OK"} default button 1 with title "Folder that will hold the tools" with icon POSIX file "/Users/Shared/Finder.icns")')
	
	HELP_FOLDER=$(/usr/bin/osascript -e 'text returned of (display dialog "Enter the name of folder 3" default answer "Help" buttons {"OK"} default button 1 with title "Folder that will hold the support documents" with icon POSIX file "/Users/Shared/Finder.icns")')
		
	echo "$(date) User provided: $TOOLS_FOLDER $REPORTS_FOLDER $HELP_FOLDER" >> $PATH_TO_LOG
else
	echo "$(date) User decided to use default values: $TOOLS_FOLDER $REPORTS_FOLDER $HELP_FOLDER" >> $PATH_TO_LOG
fi

#5. Go to the home folder.
cd $HOME

#6. Check to see if each of the folders exists. If it exists then do not create it. Else create the folder. 
echo "$(date) Creating folders: $TOOLS_FOLDER, $REPORTS_FOLDER, $HELP_FOLDER" >> $PATH_TO_LOG

for item in $TOOLS_FOLDER $REPORTS_FOLDER $HELP_FOLDER; do
	if [[ -d $item ]]; then
		echo "$(date) Not creating $item as it already exists." >> $PATH_TO_LOG
	else
		echo "$(date) Creating $item" >> $PATH_TO_LOG
		mkdir $item
	fi
	
	#7. Create the task completion file inside each folder.
	echo "$(date) Creating hidden file for $item folder." >> $PATH_TO_LOG
	cd $item
	#8. Generate the file names based on the folder names.
	touch ".$item-FolderCreated"
	cd ..
done

echo "$(date) Task completed. Have a nice day!"
	
#-------------------------------------------------------------------------------------------------
#-------------------------------------------------------------------------------------------------
#-------------------------------------------------------------------------------------------------
# ------------------------------ END OF SCRIPT ---------------------------------------------------

I have also performed some additional cleanup. That has been highlighted. The comments and the help have also been updated to reflect the new changes. I have also moved a couple of the echo statements further up the script. These have also been highlighted.

Video

Download

The completed script can be downloaded from here.

Advertisement

Creating iOS Apps without Storyboard – Part 2

Autolayout Programmatically

This article continues from the previous article. Earlier we saw how we can make iOS Apps without using the storyboard file. In this article we will explore how to implement Autolayout programmatically. We will continue from the previous article.

The code that I will be showing in the article will not be covering all the possible cases. The point of this article is to give you an idea on how to implement the different Autolayout solutions. Feel free to play around with the code to cover all the cases & situations.

Programmatic Constraints

We have 3 options when it comes to applying constraints programmatically:

  1. StackViews
  2. Layout Anchors
  3. NSLayoutConstraints class
  4. Visual Format Language (VFL)

Handling Size Classes in code

Handling Size classes in code is fairly easy. It is a simple question of overriding the correct function. We will look at this in greater detail when we cover the topic later in the article.

TopicPage
Implementing UIStackViews2
Implementing Layout Anchors3
NSLayoutConstraints class4
Implementing Visual Format Language5
Size Classes6
Summary & Video7

This article has been written using Xcode 10.3.

Creating iOS Apps without Storyboard – Part 1

What are “nibless” apps?

Apps which are designed without the help of Storyboard are called as “Nibless” apps. Normally we design an app with the help of a Storyboard file. Earlier they were called Xib files or Nib files. Hence the term “Nibless”.

Why should we create Apps without storyboard?

There are a number of reasons.

  1. It makes for a better experience when implementing along with version control.
  2. Allows us to create UI elements dynamically.
  3. Makes reusable UI Components easier to distribute and reuse.

How can we create Apps without Storyboard?

There are a couple of things that need to be done. Firstly the Main.storyboard file needs to be removed and the project settings need to be updated to reflect this change.. We are doing this since we won’t be using the storyboard file.
Everything will now have to be started up by us manually. Many of these tasks were taken care of by storyboard, but since that was removed we will have to do it. This means we have to manually create the window, create the view controller set it as a the root view controller.
We also have to manually create each and every component on our own. That is the very thing we were trying to achieve.

This example is implemented on Xcode 10.3 on macOS 10.14.5. We are not implementing auto layout in this article. We will look at implementing that programmatically in the next article.

  1. Let us start with an empty project. Open Xcode.
  2. Select File > New > Project
  3. Give it any name. Select the language as Swift & leave the checkboxes unchecked.
  4. Once the project loads select the Main.storyboard file and delete it.
  5. Switch to the Project settings file.
  6. Remove the entry for the main interface.
  7. It is a good idea to leave the LaunchScreen.storyboard file. The reason for this is to give the launch process a reference of the screen size it needs to produce. Else it will default down to the 0,0,320,480 which is the old iPhone size.
  8. Switch to the AppDelegate.swift file.
  9. Add the following property below the UI Window declaration.
      
    let mainScreenController : ViewController = ViewController() 
    
  10. Add the code to create the window and set root view controller in the didFinishLaunchingWithOptions method
       
    //1. Create the UIWindow object   
    self.window = UIWindow(frame: UIScreen.main.bounds)   
    
    //2. Set the root view controller   
    self.window?.rootViewController = self.mainScreenController   
    
    //3. Make the window key and visible  
    self.window?.makeKeyAndVisible()  
    
  11. Switch to the ViewController.swift file.
  12. Declare the following variables
      
    //UI Variables  
    var labelDemo   : UILabel?  
    var imageDemo   : UIImageView?  
    var buttonDemo  : UIButton = UIButton(type: UIButton.ButtonType.roundedRect) 
    var dataField   : UITextField?
    
  13. Implement the function to create labels. The process of creating a view programmatically is fairly straightforward. Barring a few variations depending on the view component nothing is drastically different.
      
    func createLabel() 
    {      
         //1. Specify the dimensions      
         let labelRect : CGRect   = CGRect(x: 100.0, y: 50.0, width: self.view.frame.size.width - 130.0, height: 60.0)     
    
         //2. Create the view object      
         labelDemo                = UILabel(frame: labelRect)      
    
         //3. Customise the view attributes      
         labelDemo?.text          = "This is my first Programmatic App."                
         labelDemo?.textColor     = UIColor.yellow      
         labelDemo?.textAlignment = NSTextAlignment.left  
         labelDemo?.numberOfLines = 0      
         labelDemo?.font          = UIFont.boldSystemFont(ofSize: 20.0)      
    
         //4. Add the view to the subview      
         self.view.addSubview(labelDemo!) 
    } 
    
    Let us examine the steps one by one.
     
    //1. Specify the dimensions 
    let labelRect : CGRect = CGRect(x: 100.0, y: 50.0, width: self.view.frame.size.width - 130.0, height: 60.0)
    
    This will define the dimensions of the view. As we are not implementing auto layout we will need to do this manually.
     
    //2. Create the view object
    labelDemo = UILabel(frame: labelRect) 
    
    Now that we have the dimensions we can go ahead and instantiate an instance of the label object using those dimensions. These 2 parts are the same as dragging a label from the object library onto the storyboard and placing it onto the storyboard per our requirements.
    //3. Customise the view attributes 
    labelDemo?.text          = "This is my first Programmatic App."     
    labelDemo?.textColor     = UIColor.yellow 
    labelDemo?.textAlignment = NSTextAlignment.center      
    labelDemo?.numberOfLines = 0 
    labelDemo?.font          = UIFont.boldSystemFont(ofSize: 20.0)
    
    This part is the same as changing the attributes in the attributes inspector. This is where we customise the label.
     
    //4. Add the view to the subview 
    self.view.addSubview(labelDemo!) 
    
    This last part also forms one part of dragging the label on to the storyboard. When we drag a view on to the storyboard it is placed within the main view that belongs to the ViewController. This statement completes the above process.
  14. Repeat the above steps for showing an image.
    func createImage()
    {
         //1. Specify the dimensions
         let imageRect  : CGRect  = CGRect(x: 30.0, y: 50.0, width: 60.0, height: 60.0)
    
         //2. Create the image model
         let imageModel : UIImage = UIImage(named: "logo.png")!
    
         //3. Create the view object
         imageDemo                = UIImageView(frame: imageRect)
    
         //4. Customise the view attributes
         imageDemo?.image         = imageModel
         imageDemo?.contentMode   = UIView.ContentMode.scaleAspectFit
    
         //5. Add the view to the subview
         self.view.addSubview(imageDemo!)
    }
    
    The code above is almost similar to the one created for labels except for the fact that we had to explicitly create a model object for the view. Images being different from strings, require this process to be done explicitly.
  15. Similarly let us implement the code for creating buttons
    func createButton()
    {
         //1. Specify the dimensions
         let buttonRect : CGRect = CGRect(x: 30.0, y: 220.0, width: 100.0, height: 50.0)
    
         //2. Provide the frame to the button
         buttonDemo.frame = buttonRect
    
         //3. Customise the view attributes
         buttonDemo.setTitle("Click Me", for: UIControl.State.normal)
         buttonDemo.addTarget(self, action: #selector(ViewController.clickMeTapped), for: UIControl.Event.touchDown)
    
         //4. Add the view to the subview
         self.view.addSubview(buttonDemo)
    }
    
    @objc func clickMeTapped(
    {
         print("Click me tapped!")
    }
    
    Again just minor variations here. Mainly the step to add a target function to be invoked when the button is tapped. We also need to write the target function itself.
  16. We will also implement the code to create a text field.
    func createTextField()
    {
        //1. Provide dimensions for the view
        let tfRect : CGRect             = CGRect(x: 30.0, y: 140.0, width: self.view.frame.size.width - 60.0, height: 50.0)
            
        //2. Create the view object
        dataField                       = UITextField(frame: tfRect)
            
        //3. Customise the attributes of the view
        dataField?.placeholder          = "Enter Name"
        dataField?.borderStyle          = UITextField.BorderStyle.roundedRect
        dataField?.keyboardType         = UIKeyboardType.namePhonePad
        dataField?.keyboardAppearance   = UIKeyboardAppearance.dark
        dataField?.returnKeyType        = UIReturnKeyType.go
            
        //4. Add the view to the subview
        self.view.addSubview(dataField!)
    }
    
  17. Next we need to call all these functions. I have implemented a single creator function for that.
    func createUIElements()
    {
         self.createLabel()
         self.createImage()
         self.createButton()
         self.createTextField()
    }
    
  18. Lastly we will call this function in the viewDidLoad method. Add the following lines to the viewDidLoad method.
    self.view.backgroundColor = UIColor.lightGray
    self.createUIElements()
    
    I have also added code to change the background colour so that we can see the background clearly.
  19. Run the project. Everything should appear normally.

Are there any benefits of creating apps without storyboard?

The points mentioned in the “why should we make programmatic apps?” section are some of the advantages. Beyond that there aren’t too many.
If you are looking at a team based project development then this approach is good.
There is no difference in terms of memory or performance when it comes down to apps design with or without storyboard.

Are there any drawbacks?

As can be seen from the example above, there are a couple of drawbacks

  1. The main drawback is that you can’t get a quick preview of how your app looks. You have to run the simulation every time you wish to see the end result.
  2. There is a lot more coding involved. Which can be daunting to those who are overly accustomed to designing with the help of storyboards

Note

A small point. I have left the LaunchScreen.storyboard file. I did not delete it. The reason I did that was to allow the app to allow the system to determine the dimensions on the device. If we do delete the file then the UIScreen.main.bounds return (0.0, 0.0, 320.0, 480.0) which are the old iPhone screen size settings.
While you can go ahead and make changes programmatically it is a lot easier to just leave the LaunchScreen.storyboard file there.

Carrying on from the previous point. It actually is okay if you leave the Main.storyboard file as is too. In which case you will have to skip steps 5,6,8,9,10. The code is still running programmatically but you do not have to create the main ViewController manually.

Download the Source Code

You can download the Xcode Project from this link.

Creating reusable UI Components for iOS App Development

In an earlier article I had discussed how we can create our own frameworks to easily share reusable code. In this article we will take this a little further and create our own reusable UI Components.

Points to Note:

  • The reusable component we will be creating is based on UIKit. For that reason this component can only be used in iOS Apps. However, you can follow the same steps to create a reusable component for macOS using Cocoa.
  • UI Components, distributed through a framework, do not render in the project storyboard file.
  • You should be familiar with creating Embedded Binaries (your own Framework). If you aren’t then please read this article first.
  • These projects are created on Xcode 10 with Swift 4.2

Getting Started

We will complete the implementation as a 2 step process. Here is the screen that we are planning to implement.

Creating the Reusable Framework

  1. Open Xcode and create a new Framework project.
    Screen Shot 2018-09-06 at 1.21.04 PM
  2. Name the project “UIVIdentityCard”.
    Screen Shot 2018-09-06 at 1.23.05 PM
  3. Save the project in any folder.
  4. Create a new Swift file File > New > File > Swift.
  5. Name the file “GenderType.swift”. This is where we will declare the enum that holds the Gender type that we are creating.
  6. Add the following code to the file.
     
    import Foundation 
    /** Possible scores that can be given. 
    *values* 
    `Male` 
    
    `Female` 
    
    `NotSpecified` 
    
    *functions* 
    `func toString() -> String` 
    Used to get the `String` version of the value 
    
    - Author: Arun Patwardhan 
    - Version: 1.0 
    */ 
    public enum GenderType 
    {      
         case Male      
         case Female      
         case NotSpecified 
    } 
    
    /** This extension adds the Enum to String converions capability 
    - Author: Arun Patwardhan 
    - Version: 1.1 
    */ 
    extension GenderType 
    {      
         /** This function converts from enum value to `String`         
         - important: This function does not do validation         
         - returns: `String`.         
         - requires: iOS 11 or later         
         - Since: iOS 11         
         - author: Arun Patwardhan         
         - copyright: Copyright (c) Amaranthine 2015         
         - version: 1.0 */      
         @available(iOS, introduced: 11.0, message: "convert to String")      
         func toString() -> String      
         {           
              switch self           
              {                
                   case .Male:                     
                        return "Male"                
                   case .Female:                     
                        return "Female"                
                   case .NotSpecified:                     
                        return "Not Specified"           
              }      
         } 
    } 
  7. Create a new Swift file called “PersonDetailsModel.swift”.
  8. Add the following code to the file.
    import Foundation
    
    /**  This struct represents the data that is to be shown in the ID card  
    **Variables**  
    `personName`  
    
    `personIcon`  
    
    `personDob`  
    Date of Birth  
    
    `personAddress` 
     
    `personPhone` 
     
    `personEmail` 
     
    `personCompany`
      
    `personHeight`
      
    `personWeight`  
    
    `personGender`  
    
    **Important**  There is a variable with the name `entryCount`. This variable keeps tracks of the number of stored properties that exist. The value of this variable will be used to determine the number of rows in the table.The computed property `numberOfRows` is the property used to access the value of `entryCount`.  
    
    - Author: Arun Patwardhan  
    - Version: 1.0
    */
    public struct PersonDetailsModel
    {     
         internal var entryCount : Int = 7     
         public var personName   : String = ""     
         public var personIcon   : UIImage     
         public var personDob    : Date     
         public var personAddress: String = ""     
         public var personPhone  : String = ""     
         public var personEmail  : String = ""     
         public var personCompany: String = ""     
         public var personHeight : Double? = 0.0     
         {          
              willSet          
              {               
                   if newValue == nil & personHeight != nil               
                   {                    
                        entryCount -= 1               
                   }               
                   else if newValue != nil & personHeight == nil               
                   {                    
                        entryCount += 1               
                   }          
              }     
         }     
    
         public var personWeight : Double? = 0.0     
         {          
              willSet(newValue)          
              {               
                   if newValue == nil & personWeight != nil               
                   {                    
                        entryCount -= 1               
                   }               
                   else if newValue != nil & personWeight == nil               
                   {                    
                        entryCount += 1               
                   }          
              }     
         }     
    
         public var personGender : GenderType?     
         {          
              willSet          
              {               
                   if newValue == nil & personGender != nil               
                   {                    
                        entryCount -= 1               
                   }               
                   else if newValue != nil & personGender == nil               
                   {                    
                        entryCount += 1               
                   }          
              }     
         }     
    
         public var numberOfRows : Int     
         {          
              return entryCount     
         }     
    
         public init(withName newName : String, icon newIcon : UIImage, birthday newDob : Date, address newAddress : String, phone newPhone : String, email newEmail : String, Company newCompany : String, height newHeight : Double?, weight newWeight : Double?, andGender newGender : GenderType?)     
         {          
              personName = newName          
              personIcon = newIcon          
              personDob  = newDob          
              personAddress = newAddress          
              personPhone = newPhone          
              personEmail = newEmail          
              personCompany = newCompany  
            
              if newGender != nil          
              {               
                   entryCount += 1          
              }          
              if newWeight != nil          
              {               
                   entryCount += 1          
              }          
              if newHeight != nil          
              {               
                   entryCount += 1          
              }          
    
              personHeight = newHeight          
              personWeight = newWeight          
              personGender = newGender     
         }
    }
    
    /**     This extension adds protocol conformance for the `CustomStringConvertible` protocol.     
    
    - Author: Arun Patwardhan     
    - Version: 1.1
    */
    extension PersonDetailsModel : CustomStringConvertible
    {     
         public var description: String     
         {          
              return """               
                   NAME: \(self.personName)               
                   DATE OF BIRTH:\(self.personDob)               
                   ADDRESS: \(self.personAddress)               
                   EMAIL:\(self.personEmail)               
                   PHONE:\(self.personPhone)          
              """     
         }
    }
  9. Now we will focus out attention on the View. Create a new file File > New > File > View.
    Screen Shot 2018-09-06 at 2.18.32 PM
  10. Name the view “UIVIdentityCard.swift”.
  11. Design the view as shown in the screenshot below.
    Screen Shot 2018-09-07 at 12.22.49 PM
  12. Create the corresponding“UIVIdentityCard.swift” file.
  13. Make the IBOutlet & IBAction connections for the different UI elements.
  14. Add the following code. This is how your file should look after its completed.
    /**     The UIVIdentityCard class     
    **Functions**     
    `public func load(data newPerson : PersonDetailsModel)`     
    Used to load the data for the view.     
    
    - Author: Arun Patwardhan     
    - Version: 1.0
    */
    @IBDesignableopen class UIVIdentityCard: UIView, UITableViewDelegate, UITableViewDataSource
    {     
         //IBOutlets --------------------------------------------------     
         @IBOutlet public weak var personIcon : UIImageView!     
         @IBOutlet public weak var personName : UILabel!     
         @IBOutlet public weak var personDetails : UITableView! 
    
         //Variables --------------------------------------------------     
         public var localTableData : PersonDetailsModel!     
         let nibName : String = "UIVIdentityCard"     
         var view: UIView!     
         let cellIdentifier : String = "IDCard"     
         //Functions --------------------------------------------------     
         /**     This function does the initial setup of the view. There are multiple things happening in this file.     
         1) The first thing that we do is to load the Nib file using the `nibName` we saved above. The UNIb object contains all the elements we have within the Nib file. The UINib object loads the object graph in memory but does not unarchive them. To unarchive them and get the ibjects loaded completely for use we have to instatiate the object and get the arry of top level objects. We are however interested in the first object that is there in the array which is of type `UIView`. The reference to this view is assigned to our local `view` variable.     
         2) Next we specify the bounds of our view     
         3) Finally we add this view as a subview     
    
         - important: This function does not do validation     
         - requires: iOS 11 or later, the varibale that contains the name of the nib file.     
         - Since: iOS 11     
         - author: Arun Patwardhan     
         - copyright: Copyright (c) Amaranthine 2015     
         - version: 1.0     
         */     
         @available(iOS, introduced: 11.0, message: "setup view")     
         func setup()     
         {          
              //1)          
              self.view = UINib(nibName: self.nibName, bundle: Bundle(for: type(of: self))).instantiate(withOwner: self, options: nil)[0] as! UIView          
         
              //2)          
              self.view.frame = bounds          
              
              //3)          
              self.addSubview(self.view)     
         }     
    
         public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int     
         {          
              if let count = localTableData?.entryCount          
              {               
                   return count - 2          
              }          
              return 0     
         }     
    
         public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&amp;gt; UITableViewCell     
         {          
              var cell : UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)          
    
              if nil == cell          
              {               
                   cell = UITableViewCell(style: .default, reuseIdentifier: cellIdentifier)          
              }          
    
              switch indexPath.row          
              {               
                   case 0:                    
                        let formatter = DateFormatter()                    
                        formatter.dateStyle = .medium                         
                        cell?.textLabel?.text = "Birthday\t: "+ formatter.string(from: (localTableData?.personDob)!)      
    
                   case 1:                    
                        cell?.textLabel?.text = "Email\t: " + localTableData.personEmail               
    
                   case 2:                    
                        cell?.textLabel?.text = "Phone\t: " + localTableData.personPhone               
    
                   case 3:                    
                        cell?.textLabel?.text = "Address\t: " + localTableData.personAddress               
    
                   case 4:                    cell?.textLabel?.text = "Company\t: " + localTableData.personCompany               
    
                   case 5:                    
                        cell?.textLabel?.text = "Gender\t: " + \(localTableData.personGender?.toString())!               
    
                   case 6:                    
                        cell?.textLabel?.text = "Height\t: \((localTableData.personHeight)!)"               
    
                   case 7:                    
                        cell?.textLabel?.text = "Weight\t: \((localTableData.personWeight)!)"               
                   default:                    
                        print("error")          
              }          
    
              cell?.textLabel?.font = UIFont.boldSystemFont(ofSize: 12.0)          
              cell?.textLabel?.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)          
              return cell!     
         }     
    
         //Inits --------------------------------------------------                    
         override public init(frame: CGRect)     
         {          
              super.init(frame: frame)          
              self.setup()     
         }     
         
         required public init?(coder aDecoder: NSCoder)     
         {          
              super.init(coder: aDecoder)          
              self.setup()     
         }     
    
         override open func layoutSubviews()     
         {          
         super.layoutSubviews()     
         }
    }
    
    /**     This extension adds the function to load data     
    - Author: Arun Patwardhan     
    - Version: 1.1
    */
    extension UIVIdentityCard
    {     
         /**          
         This function loads the data for the view          
         - important: This function does not do validation          
         - parameter newPerson: This is the object representing the person whose information will be displayed on the screen.          
         - requires: iOS 11 or later          
         - Since: iOS 11          
         - author: Arun Patwardhan          
         - copyright: Copyright (c) Amaranthine 2015          
         - version: 1.0     
         */    
         @available(iOS, introduced: 11.0, message: "load data")     
         public func load(data newPerson : PersonDetailsModel)     
         {          
              self.localTableData = newPerson          
              self.personIcon.image = localTableData.personIcon          
              self.personName.text = localTableData.personName          
              self.personDetails.reloadData()     
         }
    }
  15. Add the placeholder image for the image view.
  16. Select any of the simulators from the list.
  17. Press ⌘ + B to build the project.
  18. From the Project navigator select the Framework file.
    Screen Shot 2018-09-07 at 12.29.44 PM
  19. Control click and select “Show in Finder”.
  20. Copy the framework to the “Desktop”.

We are done creating the reusable framework. We will not shift our focus towards testing this framework.

Using the Framework in a project

Let us now test the framework we created. We will do this by incorporating the code in our iOS App.

  1. Create a new project. Call it “IdentityCardTest”.
    Screen Shot 2018-09-07 at 12.33.52 PM
    Screen Shot 2018-09-07 at 12.33.49 PM
  2. Save the file in a folder of your choice.
  3. Select the Project file and Embed the Framework into your project. 
    Screen Shot 2018-09-07 at 12.36.14 PM
  4. Add an image to your project, this will be the image that will be displayed in your custom view.
  5. Switch to the Main.storyboard file. Drag a UIView into the ViewControllers view.
  6. Set its identity to the UIVIdentityCard in the identity inspector. Also set its module to UIVIdentityCard.
    Screen Shot 2018-09-07 at 12.38.11 PM
  7. Create an IBOutlet for this custom view.
  8. Switch to the ViewController.swift file. Import the UIVIdentityCard framework at the top of the file.
    Screen Shot 2018-09-07 at 12.41.13 PM
  9. Add the following code to the file. We will be creating test data and displaying it on the screen using the Custom view we just designed.
    //Functions --------------------------------------------------
    /**
        This function prepares and loads the data that is to be shown in the custom view
    
    
        - important: This function does not do validation
        - requires: iOS 11 or later, the UIVIdentityCard framework.
        - Since: iOS 11
        - author: Arun Patwardhan
        - copyright: Copyright (c) Amaranthine 2015
        - version: 1.0
    */
    @available(iOS, introduced: 11.0, message: "prepares data to be shown on the ID card")
    func prepareIDCard()
    {
         let displayData : PersonDetailsModel = PersonDetailsModel(withName: "Arun Patwardhan", icon: UIImage(named: "iconHolder.png")!, birthday: Date(timeIntervalSince1970: 44_97_12_000), address: "Mumbai, Maharashtra, India", phone: "91-22-26486461", email: "arun@amaranthine.co.in", Company: "Amaranthine", height: 5.11, weight: nil, andGender: GenderType.Male)
    
         myIDCard.load(data: displayData)
    }
  10. Your completed ViewController.swift should look like this.
    Screen Shot 2018-09-07 at 12.44.32 PM
  11. Run the project. See if the view loads the way we wish.

Link to Sample Code

https://github.com/AmaranthineTech/ReusuableUIFramework

Video

Creating Reusable UI

iOS Device guide for App Developers

Developers making iOS Apps regularly come across situations where they need to find out the dimensions of the screen or the icons. This guide should give a better idea about the same.

iphones

iPhone 5S/SE iPhone 6/6S/7/8 iPhone 6+/6S+/7+/8+ iPhone X
Display Points

320×568

375×667

414×736

375×812

Pixels

640×1136

750×1334

1242×2208

1125×2436

Display Points to Pixels Ratio

1:2

1:2

1:3

1:3

Pixel Density

326 ppi

326 ppi

401 ppi

458ppi

App Icon Size in pixels

120×120

120×120

180×180

180×180

Aspect Ratio

16:9

16:9

16:9

19.5:9

ipads

  iPad Mini 2,3,4 iPad Air/iPad Air 2/iPad Pro 9.7” iPad Pro 10.5 iPad Pro 12.9”
Display Points

1024×768

1024×768

1112×834

1366×1024

Pixels

2048×1536

2048×1536

2224×1668

2732×2048

Display Points to Pixels Ratio

1:2

1:2

1:2

1:2

Pixel Density

326 ppi

264ppi

264ppi

264ppi

App Icon Size in pixels

152×152

152×152

167×167

167×167

Aspect Ratio

4:3

4:3

16:9

16:9