user3689341 user3689341 - 1 year ago 324
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"
label.center = 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?

Answer Source

You need to activate your toolbar:

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

override func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(animated)
    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]