Setting UIBarButtonItem not changing title, changi

2019-08-04 15:50发布

I have a UIBarButtonItem in the top right which says 'Edit'. When clicked, this code is called - I know so because the button is emboldened. However, the button's title does not change. Here is my code:

 // set to not editing and change buttons
        [self setEditing:YES animated:YES];
        UIBarButtonItem *doneButton = (UIBarButtonItem *)sender;
        [doneButton setTitle:@"Done"];
        [doneButton setStyle:UIBarButtonItemStyleDone];
        self.navigationItem.rightBarButtonItem = doneButton;

Edit 2:

The following code is doing what I want, however the first time I click the edit button, nothing happens.

-(void)editButton:(id)sender {
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Edit" style: UIBarButtonItemStylePlain target:self action:@selector(edit:)];

}

-(void) edit:(UIBarButtonItem *) barBtnItem
{
    // if not editing
    if (![self isEditing])
    {
        [self setEditing:YES];
        barBtnItem.tag = 1;
        [self.navigationItem.rightBarButtonItem setTitle:@"Done"];
    }
    else
    {
        [self setEditing:NO];
        barBtnItem.tag = 0;
        [self.navigationItem.rightBarButtonItem setTitle:@"Edit"];
    }
}

6条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-08-04 16:24

From "title" property on the UIBarButtonItem reference

You should set this property before adding the item to a bar. The default value is nil.

Check this qn also

查看更多
甜甜的少女心
3楼-- · 2019-08-04 16:31

The simplest solution: Just change the BarButtonItem's identifier to custom.

查看更多
来,给爷笑一个
4楼-- · 2019-08-04 16:33

Just do this

UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithTitle:@"Edit" style: UIBarButtonItemStyleBordered target:self action:@selector(edit:)];
barButton.tag = 0;
barButton.possibleTitles = [NSSet setWithObjects:@"Edit", @"Done", nil];

Just change state according to click. simple thing.

-(void) edit:(UIBarButtonItem *) barBtnItem
{
     if (barBtnItem.tag == 0)
    {
       barBtnItem.tag = 1;
       [self.navigationItem.rightBarButtonItem setTitle:@"Done"];
    }
    else
    {
        barBtnItem.tag = 0;
        [self.navigationItem.rightBarButtonItem setTitle:@"Edit"];
    } 
}
查看更多
SAY GOODBYE
5楼-- · 2019-08-04 16:33

What about this:

self.navigationItem.rightBarButtonItem = self.editButtonItem;

I think it does pretty much what you want it to do.

It changes to "Done" when tapped, and then back to "Edit" when tapped again. Furthermore it sets the view controllers editing property accordingly.

查看更多
太酷不给撩
6楼-- · 2019-08-04 16:33

You can do it via code as well as follows

UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStylePlain target:self action:@selector(doneClicked:)];
self.navigationItem.rightBarButtonItem = rightBarButton;
查看更多
Root(大扎)
7楼-- · 2019-08-04 16:39

Change type from System:Edit to Custom

查看更多
登录 后发表回答