Thursday, May 30, 2013

UIButton currentTitle example in Objective C (iOS).

UIButton currentTitle

The current title that is displayed on the button. (read-only)

@property(nonatomic, readonly, retain) NSString *currentTitle

Discussion of [UIButton currentTitle]
The value for this property is set automatically whenever the button state changes. For states that do not have a custom title string associated with them, this method returns the title that is currently displayed, which is typically the one associated with the UIControlStateNormal state. The value may be nil.

UIButton currentTitle example.
- (IBAction)buttonPressed: (id) sender
{
 UIButton *button = (UIButton*) sender;
 NSLog(@"Clicked button is: %@", button.currentTitle);
}

Example of [UIButton currentTitle].
- (IBAction)numberBtn:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected)
    {
        NSString *number = sender.currentTitle;
        showLabel.text = [showLabel.text stringByAppendingString:number];
    }
    else
    {
        NSString *newString;
        NSString *number = sender.currentTitle;
        NSString *string = showLabel.text;
        for (int i = 0; i             NSString *sub = [string substringWithRange:(NSRange){i, 1}];
            if ([sub isEqualToString:number]) {
                newString = [string substringToIndex:i];
                newString = [newString stringByAppendingString:[string substringFromIndex:i+1]];
            }
        }
        showLabel.text = newString;
    }
    [sender setTitle:@"X" forState:UIControlStateSelected];

}

UIButton currentTitle example.
NSString *digit = [sender currentTitle];
if (self.userIsInTheMiddleOfEnteringANumber) {
    self.display.text = [[[self display] text] stringByAppendingString:digit]; // All in one line!
    NSLog(@"Digit is equal to %@",digit);
    if (digit == @".") NSLog(@"That was a decimal point!");
} else {
    self.display.text = digit;
    if ([digit isEqualToString:@"."]) NSLog(@"You can't begin a number with a decimal!");
    self.userIsInTheMiddleOfEnteringANumber = YES; // If they aren't typing, now they are!
}

End of UIButton currentTitle example article.