Friday, April 22, 2016

Adding UIBarButtonItem to UIToolbar with left/right alignment

The code below shows how to add UIBarButtonItems to a UIToolbar without a UINavigationBar.

The UIBarButtonItems on UIBarButtonItem may be aligned to the left or to the right. 
The code is written in Swift 2.2 with Xcode 7.3.

Modify ViewController.swift as:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.lightGrayColor()
        
        //Toolbar 1
        let toolbar1 = UIToolbar()
        toolbar1.sizeToFit()
        toolbar1.center = CGPointMake(view.frame.width/2, 100)
        toolbar1.backgroundColor = UIColor.orangeColor()
        
        //Aligh Left
        let cancel = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: self, action: nil)
        toolbar1.items = [cancel]
        
        //Toolbar 2
        let toolbar2 = UIToolbar()
        toolbar2.sizeToFit()
        toolbar2.center = CGPointMake(view.frame.width/2, 200)
        toolbar2.backgroundColor = UIColor.blueColor()
        
        //Aligh Right
        let flexible = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: self, action: nil)
        let search = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Search, target: self, action: nil)
        toolbar2.items = [flexible, search]
        
        //Toolbar 3
        let toolbar3 = UIToolbar()
        toolbar3.sizeToFit()
        toolbar3.center = CGPointMake(view.frame.width/2, 300)
        toolbar3.backgroundColor = UIColor.greenColor()
        
        //Alight Left and Right
        let stop = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Stop, target: self, action: nil)
        let add = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: nil)
        toolbar3.items = [stop, flexible, add]
        
        view.addSubview(toolbar1)
        view.addSubview(toolbar2)
        view.addSubview(toolbar3)
    }

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

}

Result:



Related Information:

UIBarButtonItem types and UIToolbar color settings

No comments:

Post a Comment