TheDeveloperBlog.com

Home | Contact Us

CSharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript

<< Back to SWIFT

Swift UIToolbar Tutorial: UIBarButtonItem

UIToolbar. A toolbar is usually at the bottom of the iOS screen. It contains items. These can be tapped to invoke Selectors (and take actions).
Get started. Please open your object library and drag a Toolbar and a Label to your device screen. The default item "Item" is present in the Toolbar.
Add outlet. Next please add outlets to your Toolbar and Label. Control click and drag each one to your ViewController.swift file. An outlet is a Swift reference to these controls.

Name: I chose the name "simpleToolbar" for my toolbar. This tutorial is going to keep things simple.

Add code. Here is the complex part. In viewDidLoad we create a UIBarButtonItem. We specify its text and use a Plain style. We use "self" meaning the ViewController instance as the target.

Action: We use a Selector string as the action (the fourth argument to UIBarButtonItem).

String

Selector: To target a func with name "startAction" we use the string "startAction:" with an ending colon.

Items: We add the UIBarButtonItem to the "items" collection on the UIToolbar instance.

Example UIToolbar: Swift // // ViewController.swift // ExampleTimeC // // ... // import UIKit class ViewController: UIViewController { @IBOutlet weak var simpleToolbar: UIToolbar! @IBOutlet weak var simpleLabel: UILabel! var number = 0 override func viewDidLoad() { super.viewDidLoad() // Create an item to place on our UIToolbar. // ... Use "Start" as the text. // ... Use Plain as the style (this is not deprecated). // ... Use self as the target (this object is targeted). // ... Use special selector string to reach startAction func. let item1 = UIBarButtonItem(title: "Start", style: UIBarButtonItemStyle.Plain, target: self, action: "startAction:") // Add to items collection. simpleToolbar.items?.append(item1) } func startAction(barButtonItem: UIBarButtonItem) { // This func is targeted by the selector string "startAction:." // ... The parameter is required. // Write a message to the label. simpleLabel.text = "Start action \(number)" number++ } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
Selector notes. Please note the argument to "startAction." This is required for the "action" selector we specify to work. Some of these syntax rules must be learned.
Run simulator. Now let's run the iOS simulator and try out our program. When we click (simulate a tap) on the Start item, the Label's text is updated.

Note: In the screenshot, we see the "before" and "after" shots. We tap on the Start item.

A review. With UIToolbar we create a row of items. We use selector strings (actions) to link funcs in Swift to item taps. In this way we create interactive control bars.
© TheDeveloperBlog.com
The Dev Codes