LoginSignup
15
15

More than 5 years have passed since last update.

【iOS】UIButtonでカラーボタンを作成する

Posted at

カスタムクラスを定義

カスタムクラスの作成時Subclass ofをUIButtonに変更し作成を行う。
ここでは作成するカスタムクラスをColorBkgButtonとする。

ColorBkgButton.m
#import "ColorBkgButton.h"

@implementation ColorBkgButton

//デフォルトで出来るファイル
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

//背景とタイトルの編集が出来るようにする
- (id)initWithFrame:(CGRect)frame label:(NSString *)title bkgcolor:(UIColor *)rgba
{
    self = [super initWithFrame:frame];
    if(self){
        //背景色
        self.backgroundColor = rgba;
        //輪郭線を描く
        [self.layer setCornerRadius:10.0];
        [self.layer setBorderColor:[UIColor lightGrayColor].CGColor];
        [self.layer setBorderWidth:1.0];
        //タイトルの設定
        self.titleLabel.font = [UIFont boldSystemFontOfSize:18];
        [self setTitle:title forState:UIControlStateNormal];

        //通常時のボタンの色
        [self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        //押下時のボタンの色
        [self setTitleColor:[UIColor darkGrayColor] forState:UIControlStateHighlighted];
        //タイトルシャドウの設定
        [self setTitleShadowColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        self.titleLabel.shadowOffset = CGSizeMake(1, 1);
    }
    return self;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end

RGBAを定義する関数を作成

defineで宣言

ViewController.m
//RGBカラーを作る関数を定義
#define RGBA(r,g,b,a) [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a]

あとはひたすらボタンを作成

ViewController.m

@implementation ViewController
- (void)viewDidLoad
{
    [super viewDidLoad];
    // CGRectMake(X座標, Y座標, 横幅, 高さ)
    ColorBkgButton *button1 = [[ColorBkgButton alloc] initWithFrame:CGRectMake(50, 50, 120, 120) label:@"Hello World!" bkgcolor:RGBA(200, 200, 50, 1.0)];

    // ボタンをビューに追加
    [self.view addSubview:button1];

}
15
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
15