在NavigationItem中, 想要實現 Bar Button Item.System item的切換, 來達成開始搜尋藍芽與停止搜尋按鈕的轉換.
Step 1: Add Bar Button Item
先在Navigation Item中, 新增Bar Button Item且System item設定為Search
Step 2: 建立與程式的連結
Step 3: 撰寫切換按鈕圖案的程式碼
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; } }
|