iOS - NavigationItem - Bar Button Item

When developing bluetooth project, we use a button at NavigationItem to control start and stop searching bluetooth device.

Step 1: Add Bar Button Item

Add Bar Button Item at Navigation Item and set the System item is Search.

Step 2: Link UI and source code

Step 3: Control BarButtonItem Icon

1
2
3
4
5
6
7
8
9
private func changeToStopButton() {
let stopScanningButton = UIBarButtonItem( barButtonSystemItem: UIBarButtonSystemItem.Stop, target: self, action: #selector(ViewController.stopScan));
self.navigationItem.rightBarButtonItem = stopScanningButton;
}

private func changeToScanButton() {
let scanButton = UIBarButtonItem( barButtonSystemItem: UIBarButtonSystemItem.Search, target: self, action: #selector(ViewController.startScan));
self.navigationItem.rightBarButtonItem = scanButton;
}

Source Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import UIKit

class ViewController: UIViewController {
var mBtManager : BtManager!;

override func viewDidLoad() {
super.viewDidLoad()
mBtManager = BtManager();
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}

@IBAction func prepareScan(sender: AnyObject) {
startScan();
}

func startScan() {
mBtManager.startToScan();
changeToStopButton();
}

func stopScan() {
mBtManager.stopScanning();
changeToScanButton();
}

private func changeToStopButton() {
let stopScanningButton = UIBarButtonItem( barButtonSystemItem: UIBarButtonSystemItem.Stop, target: self, action: #selector(ViewController.stopScan));
self.navigationItem.rightBarButtonItem = stopScanningButton;
}

private func changeToScanButton() {
let scanButton = UIBarButtonItem( barButtonSystemItem: UIBarButtonSystemItem.Search, target: self, action: #selector(ViewController.startScan));
self.navigationItem.rightBarButtonItem = scanButton;
}
}
Author

Nick Lin

Posted on

2016-07-06

Updated on

2023-01-18

Licensed under


Comments