M.J. M.J. - 2 months ago 10
Swift Question

Adding a self populating date into the Navigation Bar Title

I want to have the current date prepopulate in the navigation bar each time the user opens the app, without having to select it using the date picker. Similar to how food tracker apps such as Lose It and MyFitness Pal work. But I can't find any documentation on how to do this. Here's what I tried but it says I can't assign NSDate to type String.

let currentDate = NSDate()
let dateFormatter = NSDateFormatter()

dateFormatter.dateStyle = NSDateFormatterStyle.FullStyle
var convertedDate = dateFormatter.stringFromDate(currentDate)
dateFormatter.dateFormat = "EEEE, MMMM dd, yyyy"
convertedDate = dateFormatter.stringFromDate(currentDate)

self.title = NSDate()

Answer

The issue is that you need to assign self.title the correct date value.

The line:

self.title = NSDate()

is assigning self.title to a new instance of NSDate(), while you want to assign it to the formatted date that you have above, convertedDate, which is also aString`.

Additionally, NSDate() is of type NSDate and not of type String. If you converted it to a String it would be unformatted.

So really, you need the line to be:

self.title = convertedDate
Comments