如何动态更改小节按钮的名称

时间:2016-08-11 08:56:04

标签: ios swift xcode rightbarbuttonitem

任何人都可以告诉我如何在更新表视图控制器中的数据时将视图控制器中名为“save”的条形按钮项目转换为“更新”。 我使用的是ios 9,xcode 7.3和swift 2.2。

我正在为条形按钮提供示例代码。

@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)")
        }

    }

2 个答案:

答案 0 :(得分:2)

viewDidLoad

中更改此标题
if (isUpdate == true) {
    let item = self.navigationItem.rightBarButtonItem
    item?.title = "Update"
}

答案 1 :(得分:2)

您可以使用viewDidLoad()方法进行此操作:

if let item = self.navigationItem.rightBarButtonItem {
      item.title = isUpdate ? "Update" : "Save"
}