iOS開發(fā)swift之設(shè)置button文字跟圖片排列任意對齊方式

//
//  Button+Extension.swift
//  Shop
//
//  Created by fox on 2020/11/25.
//  Copyright ? 2020 Aos. All rights reserved.
//
import Foundation
import UIKit
import Foundation

/// 自定義button
enum ButtonEdgeInsetsStyle {
   case ButtonEdgeInsetsStyleTop // image在上,label在下
   case ButtonEdgeInsetsStyleLeft  // image在左,label在右
   case ButtonEdgeInsetsStyleBottom  // image在下,label在上
   case ButtonEdgeInsetsStyleRight // image在右,label在左
}

extension UIButton {
    func layoutButtonEdgeInsets(style:ButtonEdgeInsetsStyle,space:CGFloat) {
      var labelWidth : CGFloat = 0.0
      var labelHeight : CGFloat = 0.0
      var imageEdgeInset = UIEdgeInsets.zero
      var labelEdgeInset = UIEdgeInsets.zero
      let imageWith = self.imageView?.frame.size.width
      let imageHeight = self.imageView?.frame.size.height
      let vue = (UIDevice.current.systemVersion) as NSString
    
        if vue.doubleValue >= 8.0 {
        
        labelWidth = (self.titleLabel?.intrinsicContentSize.width)!
        labelHeight = (self.titleLabel?.intrinsicContentSize.height)!
      }else {
        labelWidth = (self.titleLabel?.frame.size.width)!
        labelHeight = (self.titleLabel?.frame.size.height)!
      }
     
      switch style {
      case .ButtonEdgeInsetsStyleTop:
        imageEdgeInset = UIEdgeInsets(top: -labelHeight-space/2.0, left: 0, bottom: 0, right: -labelWidth)
        labelEdgeInset = UIEdgeInsets(top: 0, left: -imageWith!, bottom: -imageHeight!-space/2.0, right: 0)
      case .ButtonEdgeInsetsStyleLeft:
        imageEdgeInset = UIEdgeInsets(top: 0, left: -space/2.0, bottom: 0, right: space/2.0);
        labelEdgeInset = UIEdgeInsets(top: 0, left: space/2.0, bottom: 0, right: -space/2.0);
      case .ButtonEdgeInsetsStyleBottom:
        imageEdgeInset = UIEdgeInsets(top: 0, left: 0, bottom: -labelHeight-space/2.0, right: -labelWidth)
        labelEdgeInset = UIEdgeInsets(top: -imageHeight!-space/2.0, left: -imageWith!, bottom: 0, right: 0)
      case .ButtonEdgeInsetsStyleRight:
          // To Do print("坐標(biāo)是====\(labelWidth)=====\(space)")
        imageEdgeInset = UIEdgeInsets(top: 0, left: labelWidth+space/2.0, bottom: 0, right: -labelWidth-space/2.0)
        labelEdgeInset = UIEdgeInsets(top: 0, left: -imageWith!-space/2.0, bottom: 0, right: imageWith!+space/2.0)
      }
      self.titleEdgeInsets = labelEdgeInset
      self.imageEdgeInsets = imageEdgeInset
  }
}



?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容