扩展
UIButton
控件,自定义图片与标题位置及间距(默认展示图片在左,标题在右,二者间距默认为0)
-
Example
1) 图片在上方,文字在下方
2) 图片在左侧,文字在右侧
使用方法
- 仅一行代码即可设置图片与标题的位置(间距可设置,默认为
0
个单位)
button.adjustImageTitlePosition(.top, spacing: 6)
源码分享
//
// CCButton.swift
// HelloSwift
//
// Created by a51095 on 2021/7/15.
//
extension UIButton {
/// 逆时针方向🔄
enum Position { case top, left, bottom, right }
/// 重置图片image与标题title位置(默认间距为0)
func adjustImageTitlePosition(_ position: Position, spacing: CGFloat = 0 ) {
self.sizeToFit()
let imageWidth = self.imageView?.image?.size.width
let imageHeight = self.imageView?.image?.size.height
let labelWidth = self.titleLabel?.frame.size.width
let labelHeight = self.titleLabel?.frame.size.height
switch position {
case .top:
imageEdgeInsets = UIEdgeInsets(top: -labelHeight! - spacing / 2, left: 0, bottom: 0, right: -labelWidth!)
titleEdgeInsets = UIEdgeInsets(top: 0, left: -imageWidth!, bottom: -imageHeight! - spacing / 2, right: 0)
break
case .left:
imageEdgeInsets = UIEdgeInsets(top: 0, left: -spacing / 2, bottom: 0, right: 0)
titleEdgeInsets = UIEdgeInsets(top: 0, left: spacing * 1.5, bottom: 0, right: 0)
break
case .bottom:
imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: -labelHeight! - spacing / 2, right: -labelWidth!)
titleEdgeInsets = UIEdgeInsets(top: -imageHeight! - spacing / 2, left: -imageWidth!, bottom: 0, right: 0)
break
case .right:
imageEdgeInsets = UIEdgeInsets(top: 0, left: labelWidth! + spacing / 2, bottom: 0, right: -labelWidth! - spacing / 2)
titleEdgeInsets = UIEdgeInsets(top: 0, left: -imageWidth! - spacing / 2, bottom: 0, right: imageWidth! + spacing / 2)
break
}
}
}
更多组件 GitHub