user3689341 user3689341 - 10 months ago 196
Swift Question

Add text label to toolbar - Swift

Hi I am having trouble adding text to the toolbar contained within the navigation controller. This is what I am trying to do:

let label = UILabel(frame: CGRectMake(0, 0, 200, 21))
label.text = "Delete Pins" = CGPoint(x: CGRectGetMidX(view.frame), y: view.frame.height)
label.textAlignment = NSTextAlignment.Center

let toolbarTitle = UIBarButtonItem(customView: label)
navigationController?.toolbar.setItems([toolbarTitle], animated: true)

I am trying to get it to the text to show up here to let the user know they are in delete mode, any help?


You need to activate your toolbar:

override func viewWillAppear(animated: Bool) {
    self.navigationController?.setToolbarHidden(false, animated: false)

override func viewWillDisappear(animated: Bool) {
    self.navigationController?.setToolbarHidden(true, animated: false)

Your customView seems fine. You could also use and flexibleSpace to setup left/right/center:

    let flexible = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
    self.toolbarItems = [flexible,toolbarTitle]