Monday, April 25, 2016

Customize UIToolbar with text, textfield, button and fixed/flexible gaps

The code below shows how to customize a UIToolbar with a fixed gap, a flexible space, a text, a textfield, and a button. The code is written in Swift 2.2 with Xcode 7.3.

Modify ViewController.swift as:

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {
    var textField : UITextField!

    override func viewDidLoad() {
        //Fixed space
        let fixed = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FixedSpace, target: self, action: nil)
        fixed.width = 10
        let text = UIBarButtonItem(title: "My Title", style: UIBarButtonItemStyle.Plain, target: self, action: nil)
            NSFontAttributeName : UIFont.systemFontOfSize(23.0),
            NSForegroundColorAttributeName : UIColor.whiteColor()], forState: UIControlState.Normal)
        textField = UITextField(frame: CGRectMake(0,0,150,30))
        textField.delegate = self
        textField.textColor = UIColor.blueColor()
        let border = CALayer()
        let width : CGFloat = 2.0
        border.borderColor = UIColor.whiteColor().CGColor
        border.frame = CGRectMake(0, textField.frame.size.height-width, textField.frame.size.width, textField.frame.size.height)
        border.borderWidth = width
        textField.layer.masksToBounds = true
        let textFieldButton = UIBarButtonItem(customView: textField)
        //Search Button
        let search = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Search, target: self, action: nil)

        //Flexible Space
        let flexible = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: self, action: nil)
        let toolbar = UIToolbar(frame: CGRectMake(0,20,view.frame.width,50))
        toolbar.barTintColor = UIColor.orangeColor()
        toolbar.translucent = false
        toolbar.tintColor = UIColor.whiteColor()
        toolbar.items = [fixed, text, fixed, textFieldButton, flexible, search]
    func textFieldDidBeginEditing(textField: UITextField) {

        view.backgroundColor = UIColor.yellowColor()
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

        view.backgroundColor = UIColor.cyanColor()
        //Hide the keyboard
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        view.backgroundColor = UIColor.whiteColor()

        //Hide the keyboard
        return true

    override func didReceiveMemoryWarning() {



Related information:

Adding UIBarButtonItem to UIToolbar with left/right alignment
UIBarButtonItem types and UIToolbar color settings

No comments:

Post a Comment