Skip to content

IOS:UIButton

Button image selector

버튼을 터치하거나 비활성(Disable)상태의 경우 등, 버튼 상태에 따라서 이미지를 변경하고 싶을 경우 아래의 메소드를 사용하면 된다.

[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]; // 라벨

마지막 인자로 사용되는 State값 목록은 아래와 같다.

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

Android의 Button Widget에 있는 drawableTop속성과 같이 아이콘을 위로, 라벨(Label)을 아래로 위치시키고 싶을 경우 아래와 같이 두 메소드를 Override하면 된다.

- (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;
}