实现Button文字(titleLabel)和图片(imageView)上下排列

本文介绍了如何通过调整UIButton的titleEdgeInsets和imageEdgeInsets属性,实现按钮中文字和图片的上下排列。文中详细解释了这两个属性的作用,并提供了代码示例,帮助理解它们之间的位置关系。
摘要由CSDN通过智能技术生成
  self.personBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.personBtn setTitle:@"找人" forState:UIControlStateNormal];
    self.personBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    [self.personBtn setImage:[UIImage imageNamed:@"accompany.png"] forState:UIControlStateNormal];
    [self.personBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.personBtn addTarget:self action:@selector(accompanyAction) forControlEvents:UIControlEventTouchUpInside];

    self.personBtn.imageEdgeInsets = UIEdgeInsetsMake(3, 0, -8, -self.personBtn.titleLabel.intrinsicContentSize.width);
    self.personBtn.titleEdgeInsets = UIEdgeInsetsMake(10, -self.personBtn.imageView.frame.size.width, -self.personBtn.imageView.frame.size.height- offset/2, 0);

原文链接:

http://www.jianshu.com/p/3052a3b14a4e

1、我最开始实现这个采用的方法:
重新自定义一个view,然后有两个属性label和imageView,然后设置位置布局,再添加单击手势,用代理回传点击方法。

2、第二种方法:
自定义一个Button继承Button,有两个属性label和imageView,然后设置布局。这样就不用添加单击手势。

3、第三种方法:
直接用Button自带的titleLabel和imageView,写个Category,用来设置label和image的排列方式,eg:上下、左右

明显前两种是很不好的,所以这里只说第三种:

Button有两个属性:titleEdgeInsets和imageEdgeInsets,通过设置这两个,就可以实现所有需要的Button的样式,如:image在上、image在下、image在左、image在右。

在设置这两个之前,我们先要理解Button上面的titleLabel和imageView的位置关系(想象Button默认的image和label的显示):

  1. titleEdgeInsets是titleLabel相对于其上下左右的inset,跟tableView的contentInset是类似的;
  2. 如果只有title,那titleLabel的 上下左右 都是
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值