外見の特徴
角丸/背景だけ半透明/画像と文字を表示
環境
iOS5.0以降、ARC
必要なフレームワーク
QuartzCore.framework
インポートしておくヘッダ
#import <QuartzCore/QuartzCore.h>
手順
Custom以外だと背景の色を変更できません。
適当な名前でIBOutletとして接続。ここでは以下のように名前をつけました。
@property (weak, nonatomic) IBOutlet UIButton *flashButton;
あとはviewDidLoad内で残りの設定
- (void)viewDidLoad
{
[super viewDidLoad];
[self.flashButton setTitle:@"OFF" forState:UIControlStateNormal];
[self.flashButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[self.flashButton setImage:[UIImage imageNamed:@"flash.png"] forState:UIControlStateNormal];
[self.flashButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[self.flashButton addTarget:self action:@selector(tapFlashButton) forControlEvents:UIControlEventTouchUpInside];
[self roundButton:self.flashButton];
[self changeButtonSize:self.flashButton];
}
- (void)roundButton:(UIButton*)button{
CALayer *buttonLayer = button.layer;
CGSize buttonSize = button.bounds.size;
// ボタンが縦長/横長どちらの場合でも、それに応じた角丸半径を設定する
CGFloat buttonRadius = (buttonSize.width>buttonSize.height)?buttonSize.height/2:buttonSize.width/2;
[buttonLayer setMasksToBounds:YES];
[buttonLayer setCornerRadius:buttonRadius];
[buttonLayer setBorderWidth:1.0f];
[buttonLayer setBorderColor:[[UIColor blackColor] CGColor]];
[buttonLayer setBackgroundColor:[[UIColor colorWithRed:1.0f green:1.0f blue:1.0f alpha:0.5f] CGColor]];
}
// ボタンのサイズを調整する
// UIView animate~のブロック内でサイズ変更をアニメーションさせています。
- (void)changeButtonSize:(UIButton*)button{
CGFloat contentSize = button.imageView.bounds.size.width + button.titleLabel.bounds.size.width;
[UIView animateWithDuration:0.1f animations:^{
button.frame = CGRectMake(button.frame.origin.x, button.frame.origin.x, contentSize + 15, button.frame.size.height);
}];
}