marco
marco

Reputation: 676

Add UILabel to UIToolbar Programmatically

I am trying to add a UILabel to UIToolbar, created programmatically using the swift 3.0 language. The toolBar is to accompany the automatic keyboard called when the user is editing a UITextField.This is my function to create the toolbar (called by the viewDidLoad), which includes a 'Done' button, 'Cancel' button, and a space in between:

func createToolbar {
let toolBar = UIToolbar()
toolBar.sizetofit()
toolBar.isUserInteractionEnabled = true
textField.inputAccessoryView = toolBar 
let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(EntryViewController.doneButtonTapped))
let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(EntryViewController.cancelButtonTapped))
let space = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil)
toolBar.setItems([doneButton, space, cancelButton], animated: false)

Here is a picture of the loaded toolbar: toolBar Picture

To create the label, I am using this code:

let label = UILabel()
label.text = "Example"
let labelAsBarButtonItem = UIBarButtonItem(customView: label)
toolBar.setItems([doneButton, space, cancelButton, labelAsBarButtonItem], animated: false)
}

However, this code is not working and does not load the label on the created toolbar.

Upvotes: 5

Views: 1778

Answers (2)

TOUZENE Mohamed Wassim
TOUZENE Mohamed Wassim

Reputation: 712

EDITED ANSWER

The problem is with the label. After instanciation, you must draw it with CGRect. so, add for exemple : label.frame = CGRect(x: 20, y:20, width: 100, height: 50)

Result:

let label = UILabel()
label.text = "Example"
label.frame = CGRect(x: 20, y:20, width: 100, height: 50)

Upvotes: 0

Suhit Patil
Suhit Patil

Reputation: 12023

Below code works for me, try setting toolbar height to 44 and add it to the view

func createToolbar() {
  let toolBar = UIToolbar(frame: CGRect(x: 0, y: 64, width: view.bounds.width, height: 44))
  toolBar.isUserInteractionEnabled = true
  let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: nil)
  let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: nil)
  let space = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil)
  let label = UILabel(frame: .zero)
  label.text = "Example"
  label.textAlignment = .center
  label.textColor = view.tintColor
  let customBarButton = UIBarButtonItem(customView: label)
  let rightSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil)
  toolBar.setItems([doneButton, space, cancelButton, rightSpace, customBarButton], animated: false)
        view.addSubview(toolBar)
} 

Upvotes: 3

Related Questions