Button中UILabel和UIImage的布局

Button中UILabel和UIImage的布局

要想很好的完成Button中UILabel和UIImage的布局,我们可以简单的分成两步。

  • 确定UILabel和UIImage的位置(左右 或者 右左)
  • imageEdgeInsets titleEdgeInsets(这里用到的两个属性)
  • 将两者看成一个整体完成相应的布局
  • contentEdgeInsets(这里用到的属性)
import UIKit

var str = "Hello, playground"

let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 44))
btn.setTitle("Gaol", forState: .Normal)

let image = UIImage(named: "icon_check")
btn.setImage(image, forState: .Normal)

//默认状态
btn.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
btn.titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
btn.contentEdgeInsets = UIEdgeInsets(top: 10, left: 0, bottom: 10, right: 0)


//图在右边
let imageWidth = btn.imageView!.bounds.size.width
let labelWidth = btn.titleLabel!.bounds.size.width
btn.imageEdgeInsets = UIEdgeInsets(top: 0, left: labelWidth, bottom: 0, right: -labelWidth)
btn.titleEdgeInsets = UIEdgeInsets(top: 0, left: -imageWidth, bottom: 0, right: imageWidth)
btn.contentEdgeInsets = UIEdgeInsets(top: 10, left: 0, bottom: 10, right: 0)
默认状态
图片在右
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容