Search code examples
iphonexcode4uibuttonsettext

UIButton setTitle forState Not Working


I'm trying to set the text of a UIButton on a new view when a "Next" button is pressed from a previous view. I have set the IBOutlet correctly and I've looked all over for answers to this but it just isn't working at all.

Here is a sample of what I'm trying to do:

- (IBAction)computeQuiz:(id)sender
{  
    [fiveFootUniversalResults setTitle:@"Test" forState:UIControlStateNormal];
}

- (IBAction)jumpT10ResultsView:(id)sender
{       
    NSString *nibFileToLoad = @"JumpT10Results";

    UIDevice *device = [UIDevice currentDevice];

    if([device userInterfaceIdiom] == UIUserInterfaceIdiomPad)
    {
        nibFileToLoad = [nibFileToLoad stringByAppendingString:@"-iPad"];
    }

    JumpmasterPathfinderViewController *nextView = [[JumpmasterPathfinderViewController    alloc] initWithNibName:nibFileToLoad bundle:nil];

    // Modal view controller
    nextView.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentModalViewController:nextView animated:YES];

    [nextView release];

    [scrollView setContentSize:CGSizeMake(imageViewWidth, imageViewHeight + 44.0)];
}

These actions are both connected to a button on a previous view. The view loads fine and everything, the only problem is the text WILL NOT change on the button. I'm 100% sure I have the IBOutlets set correctly I just don't know what I am doing wrong. Any ideas?


Solution

  • It's not working because IB sets attributedTitle instead of title.

    Try this instead:

    NSAttributedString *attributedTitle = [self.myButton attributedTitleForState:UIControlStateNormal];
    NSMutableAttributedString *mas = [[NSMutableAttributedString alloc] initWithAttributedString:attributedTitle];
    [mas.mutableString setString:@"New Text"];
    
    [self.myButton setAttributedTitle:mas forState:UIControlStateNormal];
    

    Or, alternatively:

    [self.myButton setAttributedTitle:nil forState:UIControlStateNormal];
    [self.myButton setTitle:@"New Text" forState:UIControlStateNormal];
    

    (The second option won't preserve your formatting.)