实用知识:UIButton 图片在上文字在下

http://blog.csdn.net/dolacmeng/article/details/48373769

iOS默认的UIButton是图片在左文字在右,但是很多时候需求是图片在上文字在下(如效果图1、效果图2),因此想到,通过写一个JXButton继承自UIButton,并重写相关方法即可,以后项目中需要用的话就直接使用JXButton就行了。
(*以前用的另外一种方法,每次都需要写代码,使用不方便:http://blog.csdn.net/dolacmeng/article/details/45537525

新建一个类JXButton,继承于UIButton,以下是JXButtom.h的代码:

[objc] view plain copy
#import <UIKit/UIKit.h>  

@interface JXButton : UIButton  

@end  

JXButtom.m的代码:

[objc] view plain copy
//  
//  JXButton.m  
//  HXSD  
//  
//  Created by JackXu on 15/8/17.  
//  Copyright (c) 2015年 BFMobile. All rights reserved.  
//  

#import "JXButton.h"  
#import "NSString+Extension.h"  

@implementation JXButton  

-(id)initWithCoder:(NSCoder *)aDecoder{  
    if (self=[super initWithCoder:aDecoder]) {  
        self.titleLabel.textAlignment = NSTextAlignmentCenter;  
    }  
    return self;  
}  

-(id)initWithFrame:(CGRect)frame{  
    if (self=[super initWithFrame:frame]) {  
        self.titleLabel.textAlignment = NSTextAlignmentCenter;  
    }  
    return self;  
}  

-(CGRect)titleRectForContentRect:(CGRect)contentRect{  
    CGFloat titleX = 0;  
    CGFloat titleY = contentRect.size.height *0.7;  
    CGFloat titleW = contentRect.size.width;  
    CGFloat titleH = contentRect.size.height - titleY;  
    return CGRectMake(titleX, titleY, titleW, titleH);  
}  

-(CGRect)imageRectForContentRect:(CGRect)contentRect{  
    CGFloat imageW = CGRectGetWidth(contentRect);  
    CGFloat imageH = contentRect.size.height * 0.7;  
    return CGRectMake(0, 0, imageW, imageH);  
}  

@end  

使用:
(1)storyboard中:选中button,将Class设置为JXButton:

(2)如果是代码创建Button,将原来的UIButton改为JXButton即可

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值