使用自定义button自己设定button的图片和title的位置和大小

使用unbutton控件创建的对象,如果需要同时设置图片和文字的话,系统默认的式样是左图右字


比如

    UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];

    [btn setImage:[UIImage imageNamed:@"ico_st@3x"] forState:UIControlStateNormal];

    [btn setTitle:@"哈哈" forState:UIControlStateNormal];

    btn.frame = CGRectMake(100, 250, 100, 100);

    btn.backgroundColor = [UIColor redColor];

    [self.view addSubview:btn];

得到的按钮如图所示


但是,有的时候,我们需要的按钮需要其他的样式,比如,图片在上,文字在下


有许多同仁发帖所示的方法是是通过设置button.imageEdgeInset

但是,使用这个属性并不那么容易控制

我们可以通过使用自定义按钮来实现这个效果

代码如下:

创建一个类,继承于uibutton,明明为MyButton

MyButton.h

#import <UIKit/UIKit.h>


@interface MyButton : UIButton


@property(nonatomic,assign)CGRect imgRect;


@property(nonatomic,assign)CGRect titleRect;

-(instancetype)initWithtype:(UIButtonType)type WithFrame:(CGRect)frame WithImgRect:(CGRect)imgRect WithTitleRect:(CGRect)titleRect;


@end


MyButton.m

#import "MyButton.h"


@implementation MyButton


-(instancetype)initWithtype:(UIButtonType)type WithFrame:(CGRect)frame WithImgRect:(CGRect)imgRect WithTitleRect:(CGRect)titleRect{

    self = [MyButton buttonWithType:type];

    if (self) {

        self.frame = frame;

        self.imgRect = imgRect;

        self.titleRect = titleRect;

    }

    return self;

}


-(CGRect)imageRectForContentRect:(CGRect)contentRect{

    return self.imgRect;

}


-(CGRect)titleRectForContentRect:(CGRect)contentRect{

    return self.titleRect;

}


@end




在需要使用的地方调用

    CGRect r1 = CGRectMake(10, 80, 80, 20);

    CGRect r2 = CGRectMake(20, 10, 60, 60);

    MyButton * button = [[MyButton alloc] initWithtype:UIButtonTypeCustom WithFrame:CGRectMake(100, 100, 100, 100) WithImgRect:r2 WithTitleRect:r1];

    [button setTitle:@"哈哈" forState:UIControlStateNormal];

    button.titleLabel.textAlignment = NSTextAlignmentCenter;

    [button setImage:[UIImage imageNamed:@"ico_st@3x"] forState:UIControlStateNormal];

    button.backgroundColor = [UIColor redColor];

    [self.view addSubview:button];

即可实现如第二张图的效果






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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值