カスタムクラスを定義
カスタムクラスの作成時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];
}