简体   繁体   中英

How to change text of a button when another button is pressed in a different view

In my project I am trying to count the number of rows selected and then when I press the button it goes to the previous view and the button text in that view should change to how many rows are selected. I realize I must be making a simple mistake, but can't figure it out. I would appreciate some help with this.

Here is the code I am using in the .m file:

- (IBAction)doneButton:(id)sender
{
    appDelegate = (AppDelegate*) [[UIApplication sharedApplication] delegate];
    CountryModel *countryModel = [[CountryModel alloc]init];

    CompareViewController *compareViewController = [[CompareViewController alloc]init];

        [compareViewController. addCountries setTitle:[NSString stringWithFormat:@"%ld Countries Selected", countId] forState:(UIControlState)UIControlStateNormal];
        NSLog(@"%ld",countId);
//    compareViewController.addCountries.titleLabel.text = [NSString stringWithFormat:@"%ld Countries Selected", countId];
    compareViewController.Cid = countryModel.Id;
    [self.navigationController pushViewController:compareViewController animated:YES];
}

And here is the .h code for CompareViewController:

@interface CompareViewController : UIViewController

@property (assign) NSInteger Cid;
- (IBAction)addRemoveCountries:(id)sender;
@property (weak, nonatomic) IBOutlet UIButton *addCountries;

Form you code I see is you are setting the title even before the view is initialised. What you should do is add a property to your CompareViewController set it on the action. and in viewDidLoad: method of CompareViewController set this title to your button.

EDIT:

In your CompareViewController.h add a property:

@property (nonatomic, strong) NSString *buttonTitleyouNeedToSet;

In doneButton: add following ling after you initialise compareViewController

compareViewController.buttonTitleyouNeedToSet = [NSString stringWithFormat:@"%ld Countries Selected", countId];

In CompareViewController.m in viewDidLoad: set the button title:

[addCountries setTitle:buttonTitleyouNeedToSet forState:(UIControlState)UIControlStateNormal];

Do like this

AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

    NSArray *arr = appDelegate.navController.viewControllers;

    for (UIViewController *vc in arr) {
        if (vc isKindOfClass:[CompareViewController class]) {
            CompareViewController *cvc = (CompareViewController *)vc;
            [cvc.btn setTitle:@"Hello" forState:UIControlStateNormal];
            break;
        }
    }

Hope this will helpful

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM