Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add text label to toolbar - Swift

Tags:

ios

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?

like image 768
user3689341 Avatar asked Aug 09 '16 13:08

user3689341


1 Answers

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]
like image 199
derdida Avatar answered Sep 30 '22 19:09

derdida