之前遇到上图下文、下图上文的item,都是用UIImageView + Label的方式解决,过于麻烦。一直想通过设置button的图文位置来实现这种需求,但是无奈EdgeInsets总是设置不对,每次使用每次去算。某次在github上看到一个demo受到了启发,经我使用过程中改良后,现在只需要设置DirectionButton的图片方位、图片和文字的间距,即能随心所欲实现button的图文位置,即便文字宽度大于图片宽度,也能居中显示,实现需求。
//按钮中图片的位置
public enum ImageAlignment: Int {
// 默认图片在上
case top = 0
case left = 1
case bottom = 2
case right = 3
}
class DirectionButton: UIButton {
var imageAlignment: ImageAlignment = .top //默认上图下文
var spaceBetweenTitleAndImage: CGFloat = 10
override func layoutSubviews() {
super.layoutSubviews()
let space = self.spaceBetweenTitleAndImage
let titleW = self.titleLabel?.bounds.size.width
let titleH = self.titleLabel?.bounds.size.height
let imageW = self.imageView?.bounds.size.width
let imageH = self.imageView?.bounds.size.height
let btnCenterX = self.bounds.size.width / 2 //按钮中心点X的坐标(以按钮左上角为原点的坐标系)
let imageCenterX = btnCenterX - titleW!/2; //imageView中心点X的坐标(以按钮左上角为原点的坐标系)
//let titleCenterX = btnCenterX + imageW!/2;//titleLabel中心点X的坐标(以按钮左上角为原点的坐标系)
switch imageAlignment {
case .top:
self.titleEdgeInsets = UIEdgeInsetsMake(imageH!/2 + space/2, -imageW!, -(imageH!/2 + space/2), 0)
self.imageEdgeInsets = UIEdgeInsetsMake(-(titleH!/2 + space/2), btnCenterX - imageCenterX, titleH!/2 + space/2, -(btnCenterX - imageCenterX))
self.imageView?.center.x = (self.titleLabel?.center.x)!
self.titleLabel?.textAlignment = .center
case .left:
self.titleEdgeInsets = UIEdgeInsetsMake(0, space/2, 0, -(space/2))
self.imageEdgeInsets = UIEdgeInsetsMake(0, -(space/2), 0, space/2)
case .bottom:
self.titleEdgeInsets = UIEdgeInsetsMake(-(imageH!/2 + space/2), -imageW!, imageH!/2 + space/2, 0)
self.imageEdgeInsets = UIEdgeInsetsMake(titleH!/2 + space/2, btnCenterX - imageCenterX,-(titleH!/2 + space/2), -(btnCenterX - imageCenterX))
self.imageView?.center.x = (self.titleLabel?.center.x)!
self.titleLabel?.textAlignment = .center
case .right:
self.titleEdgeInsets = UIEdgeInsetsMake(0, -(imageW! + space/2), 0, imageW! + space/2)
self.imageEdgeInsets = UIEdgeInsetsMake(0, titleW! + space/2, 0, -(titleW! + space/2))
}
}
}
使用方式,其他设置与UIButton无异
let testButton = DirectionButton()
testButton.imageAlignment = .top //上图下文
testButton.spaceBetweenTitleAndImage = 3 //图片与文字之间的间距