Sunday, 15 October 2017

Create tag clouds view in swift - Tutorial



Create tag clouds view in iOS


Introduction to tutorial, how to create tag clouds view in swift:

                                       In this tutorial, we will learn how to create tag clouds view in swift. Tag clouds view, we  create will look like as show in the image view.

Cloud tags view in iOS - programmatically using swift
When user taps on cross icon we, will remove the tag and all other tags will be re-adjusted according to the width. 

Steps to create tag clouds view in swift:

Step 1: Create a new single view application and name it "TagsCloud". 

Step 2: Open "ViewController.swift", and create an IBOutlet for UITextField so that we can add a new cloud tag. Secondly, we will declare an array named "tagsArray", who will hold all our tags.


Step 3: Open Main.storyboard file and create user interface that contains one UITextField and a UIButton, as shown in the given below images, you can create your own layout too.

Intial Layout of the screen to add tags
Initial layout of our screen

Constraints used for UIButton
Constraints used for UIButton



Constraints used for UITextField
Constraints used for UITextField


 Step 4: Connect IBOutlet "txtInput" to UITextField.

Step 5: Open ViewController.swift and creates an IBAction for our UIButton.


Step 6: Open "Main.Storyboard", and connect IBAction "addTag" to UITouchUpInside event of the
UIButton.

Step 7: Next we will write definition  for recently created IBAction "addTag", here if our UITextField "txtInput" is not empty then we will add that entry to our array and call our method that we create tags cloud.


Step 8: At this time if runs your app, and press "Add Tag", button the app will gets crashed as we haven't implemented out function that will create clod tags. Copy the below code and add it to your file.



In the above function we will first remove all the sub-views whose tag is not equals to zero. Then we will get width for tags text, the add the spacing and button width as per the designs with respect to tag view. IF our tag is going outside the screen bounds then we will change x position and y position so that it will adjust to new line.
                                            Then we draw, all our elements required to create tag with cross icon and add selector to cross button so that we can remove it.

Step 9 : Last step, we are using String extension that will return string width based upon the font  that our tag is using.


Where to go from here:

     In this tutorial, you learned how to create cloud tags view in ios using swift. If you type anything in the UITextField and press "Add Tag" button. It will create a new tag. When you tap on cross icon the tags will be automatically adjusted in the cloud. If you feel any issue then please feel free to comment. You can download the source code from the given link

No comments:
Write comments