iOS UIButton 自定义图片和文字位置详解

UIEdgeInsets


typedef struct UIEdgeInsets {
    CGFloat top, left, bottom, right;  // specify amount to inset (positive) for each of the edges. values can be negative to 'outset'
} UIEdgeInsets;


UIButton中有三个对EdgeInsets的设置:ContentEdgeInsetstitleEdgeInsetsimageEdgeInsets

@property(nonatomic)          UIEdgeInsets contentEdgeInsets UI_APPEARANCE_SELECTOR; // default is UIEdgeInsetsZero
@property(nonatomic)          UIEdgeInsets titleEdgeInsets;                // default is UIEdgeInsetsZero
@property(nonatomic)          BOOL         reversesTitleShadowWhenHighlighted; // default is NO. if YES, shadow reverses to shift between engrave and emboss appearance
@property(nonatomic)          UIEdgeInsets imageEdgeInsets;                // default is UIEdgeInsetsZero


UIEdgeInsetsMake

里面的四个参数表示距离上边界、左边界、下边界、右边界的距离,默认都为零,title/image在button的正中央

UIKIT_STATIC_INLINE UIEdgeInsets UIEdgeInsetsMake(CGFloat top, CGFloat left, CGFloat bottom, CGFloat right) {
    UIEdgeInsets insets = {top, left, bottom, right};
    return insets;
}
    UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
    button.frame = CGRectMake(50, 50, 200, 60);
    [button addTarget:self action:@selector(click:) forControlEvents:(UIControlEventTouchUpInside)];
    [button setTitle:@"点击我啊" forState:(UIControlStateNormal)];
    [button setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    button.backgroundColor = [UIColor blackColor];
    [button setImage:[UIImage imageNamed:@"icon_pass"] forState:(UIControlStateNormal)];
    // 默认的是图片在左title 在右
    // 1,图片在右边,title 在左边 可以调左边距 也可以调右边距
//    button.imageEdgeInsets = UIEdgeInsetsMake(0,0,0,-150);// 和(0,150,0,0) 一样效果
//    button.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0,50); // (0,-50,0,0) 一样效果
    // 2 图片在上 title 在下面 // 具体数字可以自己调
    button.imageEdgeInsets = UIEdgeInsetsMake(- 20,50,0,0);
    button.titleEdgeInsets = UIEdgeInsetsMake(32, 0, 0,0);

    [self.view addSubview:button];


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值