まーぽんって誰がつけたの?

iOS→Scala→インフラなおじさん技術メモ

UIButtonをUITableViewCellっぽいハイライトにする

標準のUIButtonのSystemだとハイライトが文字が白くなるだけなので、それをUITableViewCellっぽくするというtipsです。

f:id:masato47744:20150127011517g:plain

実装方法は、UIButtonのサブクラスを作ってStoryboardでカスタムクラスで指定するだけです。

1. UIButtonのサブクラスを作る

@interface HighlightButton ()

@property (nonatomic) UIView *highlightView;

@end

@implementation HighlightButton

- (void)drawRect:(CGRect)rect {
    // Drawing code
    if (self.highlightView) {
        return;
    }
    
    self.highlightView = [[UIView alloc] initWithFrame:rect];
    self.highlightView.alpha = 0.0f;
    self.highlightView.backgroundColor = [UIColor colorWithWhite:0.0f alpha:0.1f];
}

- (void)setHighlighted:(BOOL)highlighted
{
    [super setHighlighted:highlighted];
    BOOL isViewAdded = [self.subviews containsObject:self.highlightView];
    if (highlighted) {
        if (!isViewAdded) {
            [self addSubview:self.highlightView];
            [self.highlightView.superview bringSubviewToFront:self.highlightView];
            [UIView animateWithDuration:0.1f
                             animations:^{
                                 self.highlightView.alpha = 1.0f;
                             }];
        }
    } else {
        if (isViewAdded) {
            [self.highlightView removeFromSuperview];
        }
    }
}

@end

2. Stoaryboardで指定する

タイプはCustomにする

f:id:masato47744:20150127012647p:plain

Customクラスに指定する

f:id:masato47744:20150127012658p:plain