This is one of those features that seems to have little documentation, isn’t used much yet it can be extremely useful.
I ran into a situation where I wanted to create these custom UIButtons to control an audioplayer. These buttons get reused in a couple of screens and I didn’t wanted to copy and paste the code to change the backgrounds nor did I want two objects.
The solution is to create a single custom UIButton class and use the Runtime Attributes.
#import <UIKit/UIKit.h> @interface AudioButton : UIButton @end |
#import "AudioButton.h" @implementation AudioButton // This method will get called for each attribute you define. -(void) setValue:(id)value forKey:(NSString *)key { if ([key isEqualToString:@"type"]) { if ([value isEqualToString:@"play"]) { [self showPlayUI]; } else { [self showStopUI]; } } } // Show the chrome for a play button - (void) showPlayUI { UIImage *playBackgroundImage = [[UIImage imageNamed:@"UIAlertSheetDefaultCancelButton.png"] stretchableImageWithLeftCapWidth:10 topCapHeight:0]; UIImage *playPressedBackgroundImage = [[UIImage imageNamed:@"UIAlertSheetDefaultButtonPressed.png"] stretchableImageWithLeftCapWidth:10 topCapHeight:0]; [self setBackgroundImage:playBackgroundImage forState:UIControlStateNormal]; [self setBackgroundImage:playPressedBackgroundImage forState:UIControlStateHighlighted]; [self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; [self setTitle:@"Play" forState:UIControlStateNormal]; } // Show the chrome for a stop button. - (void) showStopUI { UIImage *stopBackgroundImage = [[UIImage imageNamed:@"UIAlertSheetBlackTransDestroyButton.png"] stretchableImageWithLeftCapWidth:10 topCapHeight:0]; UIImage *stopPressedBackgroundImage = [[UIImage imageNamed:@"UIAlertSheetBlackTransDestroyButtonPressed.png"] stretchableImageWithLeftCapWidth:10 topCapHeight:0]; [self setBackgroundImage:stopBackgroundImage forState:UIControlStateNormal]; [self setBackgroundImage:stopPressedBackgroundImage forState:UIControlStateHighlighted]; [self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; [self setTitle:@"Stop" forState:UIControlStateNormal]; } @end |
Add the custom button to your view by dragging a UIButton onto it and changing its class to AudioButton in the identity inspector. To make the button a play button you’ll need to add a runtime attribute with its key path set to ‘type’ and its value to ‘play’.

That’s all there is to it.



