当前位置:首页 > 开发 > 移动开发 > 正文

自定义按钮, 图片在上, 文字在下, 居中显示

发表于: 2015-06-03   作者:dcj3sjt126com   来源:转载   浏览:
摘要: #import <UIKit/UIKit.h> @interface MyButton : UIButton -(void)setFrame:(CGRect)frame ImageName:(NSString*)imageName Target:(id)target Action:(SEL)action Title:(NSString*)title Font:(CGFloa
#import <UIKit/UIKit.h>

@interface MyButton : UIButton

-(void)setFrame:(CGRect)frame ImageName:(NSString*)imageName Target:(id)target Action:(SEL)action Title:(NSString*)title Font:(CGFloat)font;

@end
#import "MyButton.h"
#import "Constant.h"

@interface MyButton ()
{
        CGRect boundingRect;
}
@end

@implementation MyButton

-(void)setFrame:(CGRect)frame ImageName:(NSString*)imageName Target:(id)target Action:(SEL)action Title:(NSString*)title Font:(CGFloat)font
{
    self.frame = frame;
    [self setTitle:title forState:UIControlStateNormal];
    //设置背景图片,可以使文字与图片共存
    [self setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    [self addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    [self.titleLabel setFont:[UIFont systemFontOfSize:font]];
     boundingRect=[self.titleLabel.text boundingRectWithSize:CGSizeMake(frame.size.width, font) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]} context:nil];
}

- (CGRect)imageRectForContentRect:(CGRect)contentRect {
    CGFloat width = IsIphone6plus || IsIphone6 ? 40 : 30;
    CGFloat imageX=(self.frame.size.width-width)/2;
    CGFloat imageY=0;
    CGFloat height=width;
    return CGRectMake(imageX, imageY, width, height);
}

- (CGRect)titleRectForContentRect:(CGRect)contentRect {
    CGFloat imageX=(self.frame.size.width-boundingRect.size.width)/2;
    CGFloat imageY=contentRect.origin.y+self.imageView.bounds.size.height;
    CGFloat width=self.frame.size.width;
    CGFloat height=25;
    return CGRectMake(imageX, imageY, width, height);
}

@end

  

自定义按钮, 图片在上, 文字在下, 居中显示

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号