20
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

UIButton をグラデーションにする

Last updated at Posted at 2013-03-28

UIButton をグラデーションにする方法はググると色々あるし、NVUIGradientButton とかのライブラリもあるんだけど、単純に背景をグラデーションにしたいだけの場合色々やる必要は無かったのでメモ的に。

IKGrayButton.h
//
//  IKGrayButton.h
//  Ikuzo
//
//  Created by Haruyuki Seki on 3/28/13.
//

#import <UIKit/UIKit.h>

@interface IKGrayButton : UIButton

@end
objective-c:IKGrayButton.m
//
//  IKGrayButton.m
//  Ikuzo
//
//  Created by Haruyuki Seki on 3/28/13.
//

#import "IKGrayButton.h"
#import "UIColor+Utilities.h"
#import <QuartzCore/QuartzCore.h>

@implementation IKGrayButton

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    [self setTitleColor:[UIColor hexToUIColor:@"666666" alpha:1.0f] forState:UIControlStateNormal];
    CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.frame = self.bounds;
    gradient.colors = @[
                        (id)[[UIColor hexToUIColor: @"fdfbf3" alpha: 1.0] CGColor],
                        (id)[[UIColor hexToUIColor: @"d7d6d1" alpha: 1.0] CGColor]
                        ];
    gradient.cornerRadius = 3;
    gradient.borderColor =[[UIColor hexToUIColor:@"cccccc" alpha:1.0] CGColor];
    gradient.borderWidth = 1.0f;
    [self.layer insertSublayer: gradient atIndex: 0];

    return self;
}

@end

上記は、Storyboard 上でボタンを配置した場合のコード。Storyboard で配置したボタンのクラス指定を、上の IKGrayButton にすると以下のようなグラデーションになります。

button

ちなみに、hex で UIColor の色指定をする為に、以下のようなカテゴリ拡張を入れています。

UIColor+Utilities.m
//
//  UIColor+Utilities.m
//  Ikuzo
//
//  Created by Haruyuki Seki on 3/28/13.
//

#import "UIColor+Utilities.h"

@implementation UIColor (Utilities)
+ (UIColor*) hexToUIColor: (NSString *)hex alpha: (CGFloat)a
{
	NSScanner *colorScanner = [NSScanner scannerWithString: hex];
	unsigned int color;
	[colorScanner scanHexInt: &color];
	CGFloat r = ((color & 0xFF0000) >> 16) / 255.0f;
	CGFloat g = ((color & 0x00FF00) >> 8) / 255.0f;
	CGFloat b =  (color & 0x0000FF) / 255.0f;
	return [UIColor colorWithRed: r green: g blue: b alpha: a];
}

@end
20
19
2

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
20
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?