LoginSignup
69
70

More than 5 years have passed since last update.

角丸で枠線のUIButtonを作る

Last updated at Posted at 2015-11-21

角丸で枠線なUIButtonを作る場合、画像をBackgroudImageかImageを設定することになるのだが、たかが角丸な枠線のボタンのために画像を作るのは手間がかかる。
または、コード内で

button.layer.cornerRadius = 2.0;
button.layer.borderWidth = [UIColor BlackColor];
button.borderWidth = 1.0;

と指定してもいいのだが、毎回やるのは手間がかかるし、Storyboard上での見た目と違ってくる。

そこで、角丸で枠線のボタンが簡単に作れるUIButtonのサブクラスを作る。
このように@interfaceの前にIB_DESIGNABLE、@propertyにIBInspectable を指定すれば Storyboard上でも思った通りに表示される。

BorderButton.h
#import <UIKit/UIKit.h>

IB_DESIGNABLE
@interface BorderButton : UIButton

@property (nonatomic) IBInspectable CGFloat cornerRadius;
@property (nonatomic) IBInspectable UIColor *borderColor;
@property (nonatomic) IBInspectable CGFloat borderWidth;

@end
BorderButton.m
#import "BorderButton.h"

@implementation BorderButton

- (void)drawRect:(CGRect)rect
{
    self.layer.cornerRadius = self.cornerRadius;
    self.layer.borderColor = self.borderColor.CGColor;
    self.layer.borderWidth = self.borderWidth;

    [super drawRect:rect];
}

@end

ストーリーボードでクラスを指定すると
class指定.png

追加したパラメーターが表示されるようになるので、これを指定すると
パラメーター.png

思った通りの見た目で表示されます。
見た目.png

こちらを参考にしました
http://qiita.com/Kta-M/items/ae22fd0c78cb15faee0b
https://developer.apple.com/library/ios/recipes/xcode_help-IB_objects_media/Chapters/CreatingaLiveViewofaCustomObject.html

69
70
1

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
69
70