Help us understand the problem. What is going on with this article?

角丸で枠線のUIButtonを作る

More than 3 years have passed since last update.

角丸で枠線な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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした