如何从 UIBarButtonItem 为按钮设置标题编辑和完成?

How to set title Edit and Done for Button from UIBarButtonItem?

我有一个问题,顶部按钮没有更改自己的名称但它有效

- (IBAction)switchEdit:(UIBarButtonItem *)sender {
    sender.possibleTitles = [NSSet setWithObjects:@"Edit", @"Done", nil];
    if (sender.style == UIBarButtonSystemItemEdit){
        sender.style = UIBarButtonSystemItemDone;
        [self.navigationItem.rightBarButtonItem setTitle:@"Done"];
        self.tableView.editing = NO;
            }else{
        sender.style = UIBarButtonSystemItemEdit;
        [self.navigationItem.rightBarButtonItem setTitle:@"Edit"];
        self.tableView.editing = YES;
    }
}

考虑使用 UIViewControllereditButtonItem 属性,因为它似乎可以自动执行您需要的操作:

Returns a bar button item that toggles its title and associated state between Edit and Done.

如果你想保持你的方法,你可以将这两个按钮声明为属性并在viewDidLoad中设置它们,例如:

@interface ViewController ()

@property (nonatomic, strong) UIBarButtonItem *editBarButtonItem;
@property (nonatomic, strong) UIBarButtonItem *doneBarButtonItem;

@end

然后

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.editBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(editSelectorName)];
    self.doneBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneSelectorName)];
}

然后在您的代码中执行:

self.navigationItem.rightBarButtonItem = self.editBarButtonItem

self.navigationItem.rightBarButtonItem = self.doneBarButtonItem