UIButtonの背景色を変更する


UIButtonTypeRoundedRectタイプのUIButtonは、すっきりしていて使いやすいのですが、背景色ぐらいは設定したいですよね。でも出来ません。\(^o^)/。背景色を設定したい場合は、UIButtonTypeCustomで無色透明なボタンを作成しておき、背景と枠を自力で描画する必要があります。といっても以下のコードをコピペすればOKです。

1. ヘッダーでQuartzCore/QuartzCore.hをインポートします。

#import <QuartzCore/QuartzCore.h>

2. UIButtonTypeCustomタイプのボタンを生成し枠をつけます。

UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(50,50,100,100);
[self.view addSubview:button];
[[button layer] setCornerRadius:8.0f];
[[button layer] setMasksToBounds:YES];
[[button layer] setBorderWidth:1.0f];
[[button layer] setBackgroundColor:
    [[UIColor colorWithRed:1.0 green:0.8 blue:0.8 alpha:1.0] CGColor]];
動作イメージ
動作イメージ

サンプルプロジェクト: Button

参考:
http://stackoverflow.com/questions/4909637/uibutton-color-issues

Comments

comments

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です