Skip to content

Instantly share code, notes, and snippets.

@ryuheechul
Created October 21, 2015 06:10
Show Gist options
  • Save ryuheechul/1063a34d9fbe674b4b29 to your computer and use it in GitHub Desktop.
Save ryuheechul/1063a34d9fbe674b4b29 to your computer and use it in GitHub Desktop.
PhotoSelectButton - Objective C/iOS
#import <UIKit/UIKit.h>
@interface PhotoSelectButton : UIButton
+ (instancetype)button;
@end
#define COVER_SECTION_AREA 0.33
@implementation PhotoSelectButton
{
UIView *_coverView;
}
+ (instancetype)button
{
PhotoSelectButton *button = ({
PhotoSelectButton *b = [PhotoSelectButton buttonWithType:UIButtonTypeCustom];
b;
});
return button;
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self setupViews];
}
return self;
}
- (void)setupViews
{
[self setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
_coverView = ({
UIView *v = [[UIView alloc] init];
v.backgroundColor = [[UIColor grayColor] colorWithAlphaComponent:0.5];
v.userInteractionEnabled = NO;
v;
});
[self addSubview:_coverView];
[self setupConstraints];
}
- (void)setupConstraints
{
PhotoSelectButton *button = self;
UIView *coverView = _coverView;
coverView.translatesAutoresizingMaskIntoConstraints = NO;
NSDictionary *views = NSDictionaryOfVariableBindings(coverView,button);
[button addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[coverView(==button)]|" options:kNilOptions metrics:nil views:views]];
[button addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[coverView]|" options:kNilOptions metrics:nil views:views]];
[button addConstraint:[NSLayoutConstraint constraintWithItem:coverView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:button attribute:NSLayoutAttributeHeight multiplier:COVER_SECTION_AREA constant:0]];
}
- (void)layoutSubviews
{
[super layoutSubviews];
self.layer.cornerRadius = self.frame.size.width/2;
self.layer.masksToBounds = YES;
CGFloat coverAreaHeight = self.frame.size.height * COVER_SECTION_AREA;
CGFloat labelPadding = 2;
CGFloat fontSize = coverAreaHeight - (labelPadding * 2);
CGFloat insetTop = (self.frame.size.height - coverAreaHeight) - labelPadding * 2;
[self setTitleEdgeInsets:UIEdgeInsetsMake(insetTop, 0, 0, 0)];
self.titleLabel.font = [UIFont systemFontOfSize:fontSize];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment