Create your own Custom Input View

While working on a client project, we had to build a custom input view which allowed users to respond back soon.

UIKit allows apps to customize input views for the system keyboard, it will allow customizing the selection for the input view

After figuring out input views, I found it is easy to create your own custom input view

Let’s get started how to build a sample app to use custom input view

Final_Sample

This is how it will look after building

Creating a custom input view

Let’s create a Custom Input view named Keyboard To get started, Create a new Xcode project or open an existing project. Select File\New\File choose View in User Interface Section name the File as Keyboard, it will create a new file as Keyboard.xib

Here we can use any UI element, we have to display list of message template, we will use collection view for that

  • Drag a Collection View to view give 4 constraint to its margin
  • Make a class for keyboard xib, File\New\File in iOS section choose Cocoa Touch and subclass as UIView name it as Keyboard.swift
  • Set the nibs file owner as Keyboard.swift, please take a note that we have to set File owner as our custom class Keyboard.swift not, and make sure that the custom class for the root view is blank

file_owner

  • Make a new collection view cell
  • In xib add a textview, set its editable false and add 4 constraint to view and take a reference of it in Keyboard.swift

now put the following code in Keyboard.swift

import UIKit
protocol KeyboardDelegate: class {
    //Called when keyboard button tapped
    func keyWasTapped(character: String)
}

protocol KeyboardDataSource: class {
    //Data array for keyboard
    func dataForKeyboard()-> [String]
}

class Keyboard: UIView {
    @IBOutlet var dataCollectionView: UICollectionView!
    static let collectionViewIdentifier = "DataSelectionCell"
    fileprivate let sectionInsets = UIEdgeInsets(top: 10.0, left: 10.0, bottom: 10.0, right: 10.0)
    // This variable will be set as the view controller so that
    // the keyboard can send messages to the view controller.
    weak var delegate: KeyboardDelegate?
    // This variable will ask for data to the view controller.
    weak var dataSource: KeyboardDataSource?

    // MARK:- keyboard initialization
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        initializeSubviews()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        initializeSubviews()
    }
    // 1
    func initializeSubviews() {
        let xibFileName = "Keyboard" // xib extention not included
        let view = Bundle.main.loadNibNamed(xibFileName, owner: self, options: nil)?[0] as! UIView
        self.addSubview(view)
        view.frame = self.bounds
        //Register collection view cell
        let cellNib = UINib(nibName: Keyboard.collectionViewIdentifier, bundle: nil)
        dataCollectionView.register(cellNib, forCellWithReuseIdentifier: Keyboard.collectionViewIdentifier)
        dataCollectionView.delegate = self
        dataCollectionView.dataSource = self
    }
    // 2
    func viewTapped(gestureReconizer: UITapGestureRecognizer) {
        let point = gestureReconizer.location(in: dataCollectionView)
        let indexPath = dataCollectionView.indexPathForItem(at: point)
        // Trigger delegate for tap action
        dataCollectionView.delegate?.collectionView!(dataCollectionView, didSelectItemAt: indexPath!)
    }

}
// MARK:- UICollectionViewDelegate
extension Keyboard: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        // delegate (ie, the view controller)
        let dataArray = dataSource?.dataForKeyboard()
        let message = dataArray?[indexPath.row]
        self.delegate?.keyWasTapped(character: message!) // Inform delegate
    }
}
// MARK:- UICollectionViewDataSource
extension Keyboard: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if let dataArray = self.dataSource?.dataForKeyboard(){
            return dataArray.count
        }
        return 0
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = dataCollectionView.dequeueReusableCell(withReuseIdentifier: Keyboard.collectionViewIdentifier, for: indexPath) as! DataSelectionCell
        let dataArray = dataSource?.dataForKeyboard()
        // Add tap gesture to TextView to send tap event, as TextView will cover entire cell
        let tap = UITapGestureRecognizer(target: self, action: #selector(viewTapped(gestureReconizer:)))
        cell.dataTextView.addGestureRecognizer(tap)
        cell.dataTextView.text = dataArray?[indexPath.row] //Set text for TextView
        return cell
    }
}
// MARK:- UICollectionViewDelegateFlowLayout
extension Keyboard : UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        sizeForItemAt indexPath: IndexPath) -> CGSize {
        //Setup grid like view
        //Device screen width
        let width = UIScreen.main.bounds.size.width
        //calculation of cell size
        return CGSize(width: ((width / 2) - 15), height: (collectionView.frame.height/2) - 20 )
    }

    func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        insetForSectionAt section: Int) -> UIEdgeInsets {
        return sectionInsets
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return sectionInsets.left
    }
}

The only method in the delegate which notifies when input view button tapped. KeyboardDelegate:

func keyWasTapped(character: String)

DataSource has only one method which accepts [String] for data KeyboardDataSource

func dataForKeyboard()-> [String]
  1. Here we will initialize subviews and configure DataSource and delegate for collection view
  2. This is UITapGestureRecognizer receiver action depending on the tap it calculate selection for collection view
  3. We have added UITapGestureRecognizer to the TextView to get the selection

Usage

Use of this input view is pretty simple as we use other input views

    var keyboardView: Keyboard? //Custom view refrence
    override func viewDidLoad() {
        super.viewDidLoad()
        exampleTextView.layer.borderColor = UIColor.lightGray.cgColor
        exampleTextView.layer.borderWidth = 1
        //1
        keyboardView = Keyboard(frame: CGRect(x: 0, y: 0, width: 0, height: 216)) //Intialize custom input view
        keyboardView?.delegate = self //delegate
        keyboardView?.dataSource = self //datasource
        //2
        exampleTextView.inputView = keyboardView //Assign input view
        //Dismiss keyboard tap recognizer
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.dismissKeyboard))
        view.addGestureRecognizer(tap)
    }
  1. Initialize keyboard view with frame and set its delegate and dataSource to self
  2. Assign Keyboard view to TextView inputView

We will have to implement KeyboardDelegate method confirm the protocol

    extension ViewController: KeyboardDelegate {
        func keyWasTapped(character: String) {
            //3
            //Insert charaters to the TextView
            exampleTextView.insertText(character)
        }
    }
  1. Here we will add selected text to our textview

if you want to toggle input views then you should add IBAction for the button

    //4
    //Toggle between system and custom input view
    @IBAction func chatButtonDidTapped(_ sender: AnyObject) {
        if(exampleTextView.inputView == nil){
            // replace system keyboard with custom keyboard
            exampleTextView.inputView = keyboardView
        }
        else{
            exampleTextView.inputView = nil
        }
        exampleTextView.becomeFirstResponder()
        exampleTextView.reloadInputViews()
    }
  1. This is button action to toggle between system and custom keyboard.

This is how we have built custom input view, the final output will look like as Final_Sample_gif

You can customize it with TableView, replace with images to select the image.

You can download complete sample from Here

Custom Picker

screenCustom Picker is an easy to use and customizable alternate to UIPickerView. It is written in Swift language. The Custom Picker started as normal UIPicker but it was to limited in its design and methods. Also, I want to achieve a flat-picker with selected area background customizable which was not possible with default UIPicker.

So I made a use UITableView and customize its scroll to get the look and feel of UIPickerView. With the use of UITableView, I have made the picker flat. Now the second limitation of UIPickerView i.e. non-customizable selected area, for this I used an overlay view and customize it according to my need.

Requirements

It requires Xcode 7.0+ and Swift 2.3.

Application Usage

Custom Picker includes a sample of the project of Unit Conversion where a user can select the to and from units and input the number in one UITextField and the output will be shown in other UITextField.

Create a new picker

To use this picker you have to instantiate the CutomPickerView like instantiate any normal UIPickerView and implements it CustomPickerViewDelegate and CustomPickerViewDataSource methods

    let leftPickerView = CustomPickerView(frame: CGRectMake(0.0, 0.0, self.contentViewOfLeftpicker.frame.width,  self.contentViewOfLeftpicker.frame.height))

    leftPickerView.delegate = self
    leftPickerView.dataSource = self

    self.contentViewOfLeftpicker!.addSubview(leftPickerView)

Implement the Delegate and DataSource

The delegate methods that needs to be overridden are

func customPickerView(customPickerView: CustomPickerView, titleForRow row: Int, forLabel label: UILabel) -> String

 func customPickerView(customPickerView: CustomPickerView, didSelectRow row: Int)

func rowHeightForCustomPickerView(customPickerView: CustomPickerView) -> CGFloat

func labelStyleForCustomPickerView(customPickerView: CustomPickerView, forLabel label: UILabel)

func imageStyleForCustomPickerView(customPickerView: CustomPickerView, forImageView imageView: UIImageView)

Firstly you must rowHeightForCustomPickerView(_:)

func rowHeightForCustomPickerView(customPickerView: CustomPickerView) -> CGFloat {
        return 50.0
    }

Then you have to implement titleForRow method it sets the title for each row in a picker

func customPickerView(customPickerView: CustomPickerView, titleForRow row: Int, forLabel label: UILabel) -> String {

        return (label.tag == -1) ? pickerDataFullForm[row] as! String : pickerDataShortForm[row] as! String
    }

Next is the method that provides the didSelectRow

func customPickerView(customPickerView: CustomPickerView, didSelectRow row: Int) {

        leftPickerView.labelUnitFull.text = pickerDataFullForm[row] as? String
        leftPickerView.labelUnitShort.text = pickerDataShortForm[row] as? String

    }

Next method is labelStyleForCustomPickerView method this method is used to give custom style to UILabel in CustomPickerView

func labelStyleForCustomPickerView(customPickerView: CustomPickerView, forLabel label: UILabel) {
        if (label.tag == -1) {

            label.textColor = UIColor.blackColor()
            label.font = UIFont(name: "HelveticaNeue-Bold", size: 20.0)
        }else{

            label.textColor = UIColor.lightGrayColor()
            label.font = UIFont(name: "HelveticaNeue-Bold", size: 15.0)
        }
    }

And the last delegate method is imageStyleForCustomPickerView this is used to give any background image to the overlay view.

    func imageStyleForCustomPickerView(customPickerView: CustomPickerView, forImageView imageView: UIImageView) {
        if customPickerView == leftPickerView {
            leftPickerView.arrowImage.image = UIImage(named: "LeftArrow")
        }
    }

CustomPickerViewDataSource

The CustomPickerView consists of only one data source method. This method returns the number of rows in that picker:

 func numberOfRowsInCustomPickerView(customPickerView: CustomPickerView) -> Int

Deploying with Deploybot

I vividly remember the first time, I messed up a production server. It was my early days of being a programmer, and we had got our first client.

Back then, my deployment strategy was basically to upload files using FTP and then run any commands on the server via the shell. During a routine deployment, I noticed a file which remained in the server, and in trying to remove it, I typed sudo rm -rf /.

On the Production.

I watched the next few minutes in horror as the entire client’s machine was wiped clean and the site went down. Fortunately, my client was understanding, and we had backups – so there was not much of damage – but I had to spend the next 3 days fixing the mess (and contemplating if I am really cut out for this job.)

My biggest learning from the incident was to be very careful when on Production. Over the time, I learned Git and other tools, which made deployments more easier and safer. As someone developing in Laravel, and leading a team of Laravel developers – I am always on the look out to make deployments easier.

And I have tried everything from custom bash scripts to git workflows, where we would git pull on server. None of them however stuck primarily due to the complexities they bought in

And after much experimentation – my team and I zeroed down to DeployBot.

DeployBot allows you to deploy code from anywhere. It takes your code from your Github / Bitbucket or self hosted Git repositories and deploys to any server. At QICE, we primarily use Digital Ocean and AWS – both of which are supported by DeployBot and make it an ease to integrate in our projects.

Here’s how DeployBot has helped us

Continuous Deployment

Over the day, we make 2-3 deployments to our sandboxes on certain projects. And these are fairly large commits. DeployBot seamlessly gets the new commits and automatically ( or manual for production setups ) deploys the latest files to the server.

My team now does not have to worry about deploying to server. All we have to do is push to a branch, and we know it will end up being on the server.

Rollbacks

Despite much preparation, there are moments, when things don’t work on the production for weird reasons. Deploybot has a rollback to a specific version feature, which is quite nifty at times like these.

Pre and Post Deployment Commands

After deployment, we run a few commands ex : Gulp, Migrations and Composer updates.

Deploybot allows us to specify what commands to run before and after deployment. That means, more developer peace and not worrying about switching to server and typing in each command on production machines.

Modifying Configuration Files

Even after all this, you may have to sometimes go to the server to edit your configuration files.

Deploybot eliminates this as well, by asking you to enter your configuration files. Just ensure all the changes are in your configuration file before you deploy, and they are deployed in your next deployment.

Notifications

Pretty much every web app these days has Slack / Email integration – and so does Deploybot. It notifies us everytime there is a deployment in our Slack channels.

No more informing the entire team that the production is done and they can resume their work.

Amazing Support & Reliability

This is something of importance to us. In the past one year, that we used Deploybot, we faced a downtime of exactly 1 minute, where we couldn’t deploy to production. We reached out to Support and got a reply back within the next minute telling us that the issue has been fixed.

Thanks to Deploybot, my team and I can now focus on building stuff than worrying about getting it to our customers. If you are into developing web apps, it is an invaluable part of your toolset and takes care of all your deployment worries.