擴(kuò)展
UIButton控件,自定義圖片與標(biāo)題位置及間距(默認(rèn)展示圖片在左,標(biāo)題在右,二者間距默認(rèn)為0)
-
Example
1) 圖片在上方,文字在下方
2) 圖片在左側(cè),文字在右側(cè)
Example
使用方法
- 僅一行代碼即可設(shè)置圖片與標(biāo)題的位置(間距可設(shè)置,默認(rèn)為
0個(gè)單位)
button.adjustImageTitlePosition(.top, spacing: 6)
源碼分享
//
// CCButton.swift
// HelloSwift
//
// Created by a51095 on 2021/7/15.
//
extension UIButton {
/// 逆時(shí)針方向??
enum Position { case top, left, bottom, right }
/// 重置圖片image與標(biāo)題title位置(默認(rèn)間距為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
