Skip to content
Search

IOS:UIButton

lastmod 2018-08-17created 2014-03-194 edits

Button image selector

To change the image according to the button state, such as when the button is touched or is in the Disable state, use the following methods.

[button setImage:[UIImage imageNamed:@"icon_music_play.png"] forState:UIControlStateNormal]; // 아이콘.
[button setBackgroundImage:[UIImage imageNamed:@"bg_music_play.png"] forState:UIControlStateNormal]; // 배경이미지.
[button setTitle:@"Label" forState:UIControlStateNormal]; // 라벨

The list of State values used as the last argument is as follows.

typedef NS_OPTIONS(NSUInteger, UIControlState) {
    UIControlStateNormal       = 0,
    UIControlStateHighlighted  = 1 << 0,                  // used when UIControl isHighlighted is set
    UIControlStateDisabled     = 1 << 1,
    UIControlStateSelected     = 1 << 2,                  // flag usable by app (see below)
    UIControlStateApplication  = 0x00FF0000,              // additional flags available for application use
    UIControlStateReserved     = 0xFF000000               // flags reserved for internal framework use
};

Drawable Top

To place the icon on top and the Label below, like the drawableTop attribute of the Button Widget in Android, override the two methods as follows.

- (CGRect)titleRectForContentRect:(CGRect)contentRect
{
    CGRect titleRect = contentRect;
    titleRect.origin.y = 25;
    titleRect.size.height = contentRect.size.height - 25;
    return titleRect;
}

- (CGRect)imageRectForContentRect:(CGRect)contentRect
{
    CGRect imageRect = contentRect;
    imageRect.origin = CGPointMake((contentRect.size.width-20)/2, (contentRect.size.height-20)/2-5);
    imageRect.size = CGSizeMake(20, 20);
    return imageRect;
}