How to create tags cloud/chip layout view in swift:
Steps to create tag clouds view in swift:
Designing user inteface for chip layout in swift
Initial layout of our screen |
Constraints used for UIButton |
Constraints used for UITextField |
4: Connect IBOutlet “txtInput” to UITextField.
5: Open ViewController.swift and creates an IBAction for our UIButton.
6: Open “Main.Storyboard”, and connect IBAction “addTag” to UITouchUpInside event of the UIButton.
7: Next we will write definition for recently created IBAction “addTag”. Here if our UITextField “txtInput” is not empty then only we will add that entry to our array and call our method that we create chips or tags cloud.
Creating chip layout in swift
8: At this time if runs your app, and press “Add Tag” button, app will gets crashed as we haven’t implemented our function who is responsible for creating chips or cloud of tags. Copy the below code and add it to your file.
In the above function, we first remove all the sub-views whose tag is not equals to zero. Then we will get width for tags as per the tag name, and finally we add the spacing and button width to the chip ot tag name width we got earlier. 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 finally, we draw all our elements required to create tag with cross icon and add selector to cross button so that we can remove it.
9 : Last step, we are using String extension that will return string width based upon the font that our tag is using.