自定义按钮(图像在上面 文字在下面)


 1 @implementation ViewController
 2 
 3 - (void)viewDidLoad {
 4     [super viewDidLoad];
 5     // Do any additional setup after loading the view, typically from a nib.
 6     MYButton *btn = [MYButton buttonWithType:UIButtonTypeCustom];
 7     btn.backgroundColor = [UIColor redColor];
 8     [btn setImage:[UIImage imageNamed:@"57"] forState:UIControlStateNormal];
 9     [btn setTitle:@"会计电算教学" forState:UIControlStateNormal];
10     btn.frame = CGRectMake(100, 100, 87 , 80);
11     [self.view addSubview:btn];
12     
13 }

 

@implementation MYButton

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [self setUp];
    }
    
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super initWithCoder:aDecoder]) {
        [self setUp];
    }
    return self;
}

- (void)setUp
{
    [self setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.titleLabel.font = [UIFont systemFontOfSize:14];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    self.imageView.x = 15;
    self.imageView.y = 5;
    self.imageView.contentMode =UIViewContentModeScaleAspectFill;
    self.titleLabel.y =CGRectGetMaxY(self.imageView.frame ) +5;
    self.titleLabel.x = 0;
    self.titleLabel.width = self.width;
    
}

- (void)setTitle:(NSString *)title forState:(UIControlState)state
{
    [super setTitle:title forState:state];
    
    [self sizeToFit];
}

- (void)setImage:(UIImage *)image forState:(UIControlState)state
{
    [super setImage:image forState:state];
    
    [self sizeToFit];
}

@end

通过自定义按钮可以达到图像在上面  文字在下面  只要调整一下按钮的大小 就可以轻松的实现应用图片+应用名称的组合,非常方便做应用推荐的开发。

posted @ 2015-05-04 22:49  秋叶飘渺  阅读(268)  评论(0编辑  收藏  举报