iOS UIButton Introduction

Buttons are the most commonly used and simplest controls in iOS applications and are often used to respond to user actions. Generally, we use UIButton class to implement the button in iOS. This section will focus on adding buttons, beautifying buttons, and how to implement button responses.

1. Add iOS Button In Source Code.

  1. To add a button to the main view in source code, you first need to instantiate a button object using the UIButton class, then set the location and size, and finally add the button object to the main view using the addSubview() method.
  2. The following code adds a button object with an orange background color to the main view.
    import UIKit
    class ViewController: UIViewController {
        
            override func viewDidLoad() {
                super.viewDidLoad()
            
                // Create UIButton object.
                let button=UIButton(frame: CGRect(x: 143, y: 241, width: 88, height: 30)) 
    
                button.backgroundColor=UIColor.orange
            
                // Add UIButton object.
                self.view.addSubview(button)
            }
            ......
    }
  3. When you run the program, you can see the below picture.
    add-button-in-source-code-screen

 

2. Beautify The Button.

  1. Beautify a button is simply setting the properties of the button. There are two ways to set the button properties.
  2. One way is to use the property inspector in the interface builder.
  3. The other way is to set it by source code. The following sections will focus on how to use source code to set buttons properties.

2.1 Set Button Appearance.

  1. You can set up the button’s title, image, etc to change the button’s appearance.
  2. Below lists some of the commonly used methods for setting button appearance.
  3. setBackgroundImage: Sets the background image of the button.
  4. setImage: Set button image.
  5. setTitle: Set button title.
  6. setTitleColor: Set button title color.
  7. setTitleShadowColor: Set button title shadow color.
  8. The below code will add a button to the main view. The title of this button is ‘Click Me’ and the color of the title is black.
    import UIKit
    class ViewController: UIViewController {
            override func viewDidLoad() {
            super.viewDidLoad()
            
            // Create button.
            let button=UIButton(frame: CGRect(x: 135, y: 241, width: 97, height: 30)) 
            
            // Set button title.
            button.setTitle("Click Me", for: UIControlState.normal) 
            
            // Set button title color.
            button.setTitleColor (UIColor.black, for: UIControlState.normal) 
            
            // Add button to the main view.
            self.view.addSubview(button)
            }
            ......
    }

2.2 Set Button State.

  1. When setting the title and color of the button, the state of the button also needs to be set.
  2. Button state indicating what the title and title color of the button will look like in a certain state. For example, UIControlState.normal represents the normal state of a button.
  3. A view object like a button that can accept user input is also called a control. These controls all have their own state. Below is the control state list.
  4. normal: normal state.
  5. highlighted: highlight state.
  6. disabled: disable state and do not accept any events.
  7. selected: selected state.
  8. application: application flags.

2.3 Set Button Type.

  1. There are various types of buttons. For example, in the address book, the button to add new contact is a plus (+), while the button to see the details of the call is an exclamation point, etc.
  2. All these button types can be implemented using UIButtonType when instantiating the button object.
  3. Below is the UIButtonType list.
  4. system: System default style button.
  5. custom: Custom style button.
  6. detailDisclosure: Blue exclamation point button, mainly used for detail description.
  7. infoLight: Bright color exclamation point.
  8. infoDark: Dark exclamation point.
  9. contactAdd: The cross plus button, which is usually used as the add contact entry.
  10. The following code adds two different styles of buttons to the main view.
    import UIKit
    class ViewController: UIViewController {
            override func viewDidLoad() {
            super.viewDidLoad()
    
            // Add first button with contactAdd type.
            let button1=UIButton(type: UIButtonType.contactAdd) 
            button1.center=CGPoint(x: 190, y: 250) 
            self.view.addSubview(button1)
    
            // Add second button with detailDisclosure type.
            let button2=UIButton(type: UIButtonType.detailDisclosure) 
            button2.center=CGPoint(x: 190, y: 450) 
            self.view.addSubview(button2)
            }
            ......
    }
  11. When you run the program, you can see the below effect.
    contact-add-and-detail-disclosure-type-button

 

3. Add Button Response.

  1. There are two methods to add a button response code, one is through interface builder, the other is through source code.

3.1 Use interface builder to add button response code.

  1. Add a button using the interface builder can use drag and drop to implement the button response code, which is also the simplest way to implement button response.
  2. The following steps will implement a button that will change the main view background color when users tap it.
  3. Open the Main.storyboard file, drag the button control from the view library to the main view, and set the title to “Tap me, Change View Color“.
  4. Click the Show the Assistant editor button to show and adjust the Xcode interface builder.
  5. Hold down the Ctrl key and drag the button object in the interface, and a blue line appears, dragging the blue line to the white space of the ViewController.swift file.
  6. When you release the mouse, a dialog box that declares the associated socket variable will pop up.
  7. Set the Connection option to Action to indicate that an Action is associated. Set the Name to tapButton, indicate that the associated action is named tapButton, but you can specify any name here.
  8. Click the Connect button and you’ll see the code in the ViewController.swift file. Now a method called tapButton() will be triggered when the user taps the button.
  9. Note: the above method binds the action declaration and UI object association at the same time, and there is also another way to declare the action before it is associated.
  10. To declare an action method you can use the keyword IBAction. This keyword tells the Main.storyboard that this method is an operation method and can be triggered by a control.
  11. After declaring an action, a small hollow circle appears in front of the code, indicating that the action has not been associated.
  12. After the action is declared, the association can be made. First, use the tool in the adjustment window to adjust the interface builder. Then, hold down the Ctrl key and drag the button object in the interface, and a blue line appears, associating the blue line with the action in the file ViewController.swift.
  13. Finally, when the mouse is released, the button object is associated with the action method. At this point, the hollow circle in front of the action becomes a solid circle, which indicates that the action has been associated.
  14. Open the ViewController.swift file and write the code that will implement the button response.
    import UIKit
    class ViewController: UIViewController {
    
        var isYellow:Bool=false
    
        @IBAction func tapButton(_ sender: AnyObject){
             
            if(isYellow){
               self.view.backgroundColor=UIColor.white
               isYellow=false
            }else{
               self.view.backgroundColor=UIColor.yellow
               isYellow=true
            }
            
        }
    }

3.2 Use code to add button response.

To add a response method to the button that is created in the source code, you need to use the addTarget (action:for:) method. The syntax is as follows.

3.2.1 func addTarget(_ target: AnyObject?, action: Selector, for controlEvents: UIControlEvents)
  1. target: Represents the target object. It is the sender of the action message.
  2. action: Represents a selector used to identify the action method. It must not be empty.
  3. controlEvents: Represents control events that trigger the action method.
3.2.2 There are 19 control events in iOS.
  1. touchDown: Single touch press event: when a user touches the screen, or when a new finger drops.
  2. touchDownRepeat: Multi-touch press event, the touch count is greater than 1: when the user presses the second, third, or fourth finger.
  3. touchDragInside: When a touch is dragged inside the control window.
  4. touchDragOutside: When a touch is dragged outside the control window.
  5. touchDragEnter: When a touch is dragged from the control window outside to inside.
  6. touchDragExit: When a touch is dragged from the inside of the control window to the outside.
  7. touchUpInside: All touch lift events within the control.
  8. touchUpOutside: All touch lift events outside the control.
  9. touchCancel: All touch cancellation events, such as when a touch is canceled due to place too many fingers on the screen or is interrupted by a lock or a phone call.
  10. valueChanged: Send notifications when the value of the control changes. Used for controls like sliders, segmented controls, etc. Developers can configure when the slider control sends notifications.
  11. editingDidBegin: Send notifications when editing begins in a text control.
  12. editingChanged: Send notifications when text in a text control is changed.
  13. editingDidEnd: Send notifications when editing in a text control is finished.
  14. editingDidEndOnExit: A notification is sent when editing in a text control ends by pressing the enter key (or equivalent action).
  15. allTouchEvents: Notifies all touch events.
  16. allEditingEvents: Notifies all events about text editing.
  17. applicationReserved: Application reserved events.
  18. systemReserved: All the system reserved events.
  19. AllEvents: Contains all events.
  20. The below code will change the main view background color when tapping the button.
    import UIKit
    class ViewController: UIViewController {
            var isCyan:Bool=false
    
            override func viewDidLoad() {
                super.viewDidLoad()
    
                let button=UIButton(frame: CGRect(x: 90, y: 545, width: 225, height: 30))
    
                button.setTitle("Tap me,Change View Color", for: UIControlState())
    
                button.setTitleColor (UIColor.black, for: UIControlState())
    
                self.view.addSubview(button)
    
                button.addTarget(self, action:#selector(UIViewController.tapbutton), for:UIControlEvents.touchUpInside)
            }
    
            @objc func tapbutton(){
                if(isCyan){
                    self.view.backgroundColor=UIColor.white
                    isCyan=false
                }else{
                    self.view.backgroundColor=UIColor.cyan
                    isCyan=true
                }
            }
    }

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Clicky