最近再次学习Swift,所以会翻译一些之前OC常用的一些组件
今天要介绍的是Swift中实现UIButton内部图片与文字的布局调整,下面是效果图,先简单的看一下左右布局
上下布局
这种方式我们可以通过自定义按钮去实现,也可以通过分类去实现,既然能通过分类解决的问题,就没有必要去自定义一个新的按钮了,笔者在开发过程中还是比较喜欢使用分类去解决一些问题的
我们先来来看下一如何去调用
leftBtn.sg_setImage(location: .left, space: 10) { (btn) in
btn.setTitle("left btn", for: .normal)
btn.setImage(UIImage.init(named: "test_img"), for: .normal)
}
一句代码搞定是不是很爽,这是带有block的方法,推荐使用,在block内部进行设置按钮的文字及颜色,由于是调整图片与文字布局,那就必须先设置文字与图片才能调整,所以推荐使用带有block的方法去掉用,笔者工作中也是一直使用这种方式
再来看一下内部实现代码
///
/// Set image location
///
/// Image and title must be set before this method will work
///
/// - parameter location: Location of image relative to title
/// - parameter space: Space between image and title
///
func sg_setImage(location: SGImageLocation, space: CGFloat) {
let imageView_Width = self.imageView?.frame.size.width
let imageView_Height = self.imageView?.frame.size.height
let titleLabel_iCSWidth = self.titleLabel?.intrinsicContentSize.width
let titleLabel_iCSHeight = self.titleLabel?.intrinsicContentSize.height
switch location {
case .left:
if self.contentHorizontalAlignment == .left {
self.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: space, bottom: 0, right: 0)
} else if self.contentHorizontalAlignment == .right {
self.imageEdgeInsets = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: space)
} else {
let spacing_half = 0.5 * space;
self.imageEdgeInsets = UIEdgeInsets.init(top: 0, left: -spacing_half, bottom: 0, right: spacing_half)
self.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: spacing_half, bottom: 0, right: -spacing_half)
}
case .right:
let titleLabelWidth = self.titleLabel?.frame.size.width
if self.contentHorizontalAlignment == .left {
self.imageEdgeInsets = UIEdgeInsets.init(top: 0, left: titleLabelWidth! + space, bottom: 0, right: 0)
self.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: -imageView_Width!, bottom: 0, right: 0)
} else if self.contentHorizontalAlignment == .right {
self.imageEdgeInsets = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: -titleLabelWidth!)
self.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: imageView_Width! + space)
} else {
let imageOffset = titleLabelWidth! + 0.5 * space
let titleOffset = imageView_Width! + 0.5 * space
self.imageEdgeInsets = UIEdgeInsets.init(top: 0, left: imageOffset, bottom: 0, right: -imageOffset)
self.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: -titleOffset, bottom: 0, right: titleOffset)
}
case .top:
self.imageEdgeInsets = UIEdgeInsets.init(top: -(titleLabel_iCSHeight! + space), left: 0, bottom: 0, right: -titleLabel_iCSWidth!)
self.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: -imageView_Width!, bottom: -(imageView_Height! + space), right: 0)
case .bottom:
self.imageEdgeInsets = UIEdgeInsets.init(top: titleLabel_iCSHeight! + space, left: 0, bottom: 0, right: -titleLabel_iCSWidth!)
self.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: -imageView_Width!, bottom: imageView_Height! + space, right: 0)
}
}
最后附上代码下载地址 内部有一些平时工程中需要的一些分类