DEV Community

Cover image for UIButtons in Swift
Neeraj Gupta for DSC CIET

Posted on

UIButtons in Swift

Overview

A control that executes your custom code in response to user interactions. In simple language it means that it is a controller that gets in action when user interact with it using code.

Heirarchy of UIButton

class UIButton : UIControl
class UIControl : UIView
class UIView : UIResponder
class UIResponder : NSObject
class NSObject

Alt Text

UIButton Class Heirarchy

A little introduction to each class on which UIButton is made.

1. NSObject

This class is the one which was previously used back when all code was written in Objective-C.It is a group of methods that are fundamental to all Objective-C objects means UIButton is made on top of NSObject block on our storyboard or we can say every button will be contained in this Object.

2. UIResponder

An abstract interface for responding to and handling events means this class is responsible for handling all code when we click on button.

3. UIView

An object that manages the content for a rectangular area on the screen means it is responsible for showing us content on our screen.

4. UIControl

The base class for controls, which are visual elements that convey a specific action or intention in response to user interactions. This conveys about what type of interaction and where user has clicked on screen and pass that to code.

Why we need to inherit/use these classes ?

So, consider the scenario in which we had to create everything from scratch and we don't have Apple's object library. How hard and time consuming that task will be?. So, what Apple did was made their own UIKit in which all these reusable objects are already made by developers at Apple and are free to use by us.
These objects are made by inheriting from different classes and combining all the functionalities of different classes to make a final object.
If, this was not present then every time we will have to make a empty object make controller for it and make it responsive to user interactions and have to view that and then finally our button would have been possible. But, thanks to Apple's UIKit, this is all inbuilt and we just had to drag that into our storyboard and we are good to use it.

What is inheriting?

Word 'Inherit' might prick you is you are new to programming. Inheriting is a part of Object Oriented Programming and it means the same as title suggests us that is inherit which means getting features/properties of another class. Let's say a parent taught his/her chld to walk and talk that is what child is inheriting and let's say child learn swimming and that is now his/her own trait and not the one inherited from parent.There are lot of examples but for now this is out of scope for this blog. You can search more on google about inheritance.

How to create a button using Interface Builder?

  1. Open your Xcode project.
  2. Go to main.storyboard. Alt Text
  3. and press CMD+Shift+L or click on + button in top right corner, this will open object library. Alt Text
  4. Serch for button and drag it onto View Contoller. Alt Text Note : View Controller is one responsible to show our content on Apple Device.
  5. Your now have a button. Alt Text

How to edit you UIButton

  1. Now, once your button is placed on view controller you can chnage it's attributes/properties by pressing CMD+Option+0 this will open left sidepan and then navigate to Attributes Inspector. Alt Text
  2. Now you can tinker with different properties of UIButton using Attributes Inspector.
  3. For changing title change the text in field under title input label. Alt Text

How to change properties with code?

  1. Go to Identity Inspector in right side pane and check if your view controller is connected to ViewController.swift class and if not click on drop down arrow and select one. Alt Text Alt Text
  2. Now, our storyboard's view controller is connected to ViewController class.
  3. Press Control+Option+CMD+Enter/return or you can go to Editor in top bar and select Assistant under it to open Assistant editor, this will open your storyboard and ViewController.swift side by side. Alt Text
  4. Now click on button and drag to ViewController.swift file under class ViewController : UIViewController and override func viewDidLoad() and create IBOutlet means a reference of that button and name it and press Connect. Alt Text
  5. Now, we have refernce of that button.
  6. viewDidLoad is like main function which first intializes when our app start.
  7. So we are going to put our code here.
  8. Here i am showing how to change title of button using code.
    9.

    import UIKit
    
    class ViewController: UIViewController {
    
    @IBOutlet weak var button1: UIButton!
    override func viewDidLoad() {
      super.viewDidLoad()
      button1.setTitle("Press Me", for: .normal)
      button1.frame = CGRect(x: 184, y: 453, width: 200, height: 200)
      }
    }
    

Alt Text

  1. Now, click on Play button to run the app. Note : In my case i used iPhone 11 so change x, y, width, height accordingly.
  2. Output should look like this Alt Text

How to make button do actions?

  1. Create a IBAction same as we created IBOutlet by selecting button and pressing Control key and dragging onto storyboard. Alt Text Note : Change Type to UIButton
  2. After connecting it should look like Alt Text
  3. Everything we write in IBAction will be run on clicking button connected.
  4. Like if we want to change color on tapping button we can use
 @IBAction func changeColor(_ sender: UIButton) {
        self.view.backgroundColor = .red
    }
Enter fullscreen mode Exit fullscreen mode

Note: instead of red you can choose any color
Alt Text

  1. Now,run and tap on button to see the effect.
  2. Output will look like Alt Text

How to search if you get stuck on any step?

Stackoverflow -- This is must use site for developers, one can just search their queries related to coding here.

Apple developer -- Official documentation by Apple, you can search for classes and objects about here.

Good Bye Folks see you soon in next blog.

Top comments (5)

Collapse
 
lukeswitz profile image
Luke Switzer

Very general; Programmatic creation/events would prove a helpful addition for those who were taught without IB or use specific event listeners.

This is the link you want, stackoverflow not so much:
developer.apple.com/documentation/...

Collapse
 
neeraj15022001 profile image
Neeraj Gupta

Actually i quite didn't get these events i do read documtation but can you elaborate how we can combine events and buttons

Collapse
 
neeraj15022001 profile image
Neeraj Gupta

Sure, will look into this

Collapse
 
lukeswitz profile image
Luke Switzer

Thanks! I realize that came off as snarky, but I only meant Stackoverflow often hosts outdated, deprecated or insecure code. I love the place & contribute often, but it does damage to novice devs on a path of true learning.

Apple docs are the most up to date info you’ll find while coding in Swift/Objective-C albeit lacking somewhat in teachable examples. Learning to code it out really teaches the power of UIKit by doing: maybe the best thing I did in 20 years was stop looking at examples and start looking at best practices.

Thanks for the post; an excellent intro to how simple it is to get started with native iOS dev.

Thread Thread
 
neeraj15022001 profile image
Neeraj Gupta

Thanks for the advice and appreciation. Gave me motivation to write more.