Search code examples
objective-ccocoa-touchuibuttonuikitibaction

Can't change the caption of a UIButton from its own Touch Up Inside event


I just noticed this crazy behavior in UIButton:

If I try to set the caption of a UIButton from an IBAction that gets fired on the button's touch up inside event, the caption changes, but is quickly reverted to the old value.

If I do it in some other button's touch up inside event, it works as expected.

What monkey business is going on???

- (IBAction)removeText:(id)sender {

    [[sender titleLabel] setText:@"New Text"];

}

Solution

  • titleLabel is a read-only property. You want to use:

    [sender setTitle:@"title" forState:UIControlStateNormal];
    

    Edit: Actually, looking it up the titleLabel's own properties are still accessible, but nevertheless the setTitle solution is the way to go....