Adding a UILabel to a UIToolbar

前端 未结 8 1693
青春惊慌失措
青春惊慌失措 2020-11-27 10:24

I\'m trying to add a label to my toolbar. Button works great, however when I add the label object, it crashes. Any ideas?

UIBarButtonItem *setDateRangeButton         


        
8条回答
  •  时光取名叫无心
    2020-11-27 10:49

    I found answerBot's answer very useful, but I think I found an even easier way, in Interface Builder:

    • create a UIBarButtonItem and add it to your Toolbar in Interface Builder

    enter image description here

    • Uncheck "enabled" for this BarButtonItem

    enter image description here

    • plug this BarButtonItem to a property in your class (this is in Swift, but would be very similar in Obj-C):

      @IBOutlet private weak var lastUpdateButton: UIBarButtonItem! // Dummy barButtonItem whose customView is lastUpdateLabel
      
    • add another property for the Label itself:

      private var lastUpdateLabel = UILabel(frame: CGRectZero)
      
    • in viewDidLoad, add the following code to set the properties of your label, and add it as the customView of your BarButtonItem

      // Dummy button containing the date of last update
      lastUpdateLabel.sizeToFit()
      lastUpdateLabel.backgroundColor = UIColor.clearColor()
      lastUpdateLabel.textAlignment = .Center
      lastUpdateButton.customView = lastUpdateLabel
      
    • To update the UILabel text:

      lastUpdateLabel.text = "Updated: 9/12/14, 2:53"
      lastUpdateLabel.sizeToFit() 
      

    Result :

    enter image description here

    You have to call lastUpdateLabel.sizetoFit() each time you update the label text

提交回复
热议问题