2

Can anyone please let me know how to convert the bar button item named as "save" to "update" in view controller while updating the data in table view controller. I am using ios 9, xcode 7.3 and swift 2.2.

I am providing the sample code for the bar button.

@IBAction func save(sender: UIBarButtonItem) {

//func Plus(sender: AnyObject) {

    if isUpdate == true{
        print("object id \(self.store?.objectID)")
        self.store?.sTitle = titlename.text
        self.store?.sNote = note.text
        //save.setTitle("my text here", forState: .Normal)
        let img = UIImage(named: "image.jpg")
        let imgData = UIImageJPEGRepresentation(img!,1)
        self.store?.sImage = imgData
        do {
            try appdelegate.managedObjectContext.save()
            self.navigationController?.popViewControllerAnimated(true)
        } catch let error as NSError  {
            print("Could not save \(error), \(error.userInfo)")
        }

    }else{
        //get the description of the entity
        let storeDescription = NSEntityDescription.entityForName("Store",inManagedObjectContext: appdelegate.managedObjectContext)

        //we create managed object to be inserted to core data
        let store = EventsandnotesStore(entity : storeDescription!,insertIntoManagedObjectContext:appdelegate.managedObjectContext)
        store.sTitle = titlename.text
        store.sNote = note.text

        let img = UIImage(named: "image.jpg")
        let imgData = UIImageJPEGRepresentation(img!,1)

       store.sImage = imgData
        do {
            try appdelegate.managedObjectContext.save()
            self.navigationController?.popViewControllerAnimated(true)
        } catch let error as NSError  {
            print("Could not save \(error), \(error.userInfo)")
        }

    }
Nirav D
  • 71,513
  • 12
  • 161
  • 183
Guru Teja
  • 127
  • 2
  • 13

2 Answers2

4

Change title like this in your viewDidLoad

if (isUpdate == true) {
    let item = self.navigationItem.rightBarButtonItem
    item?.title = "Update"
}
Nirav D
  • 71,513
  • 12
  • 161
  • 183
  • I tried it but got the error as bool?cannot be used as boolean – Guru Teja Aug 11 '16 at 11:31
  • You have created your boolean with optional wrapping so either change your declaration of boolean like this `var isUpdate = false` or use `== true` with your if condition. – Nirav D Aug 11 '16 at 11:51
2

You could make this in the viewDidLoad() method:

if let item = self.navigationItem.rightBarButtonItem {
      item.title = isUpdate ? "Update" : "Save"
}
Alessandro Ornano
  • 34,887
  • 11
  • 106
  • 133