Swift button 设置图片位置

  • 在开发过程中经常遇到 按钮 与图标的放置问题,有时按钮中图片与文字的位置需要我们设置。

  • 一种方法是我们根据具体情况利用titleEdgeInsets、imageEdgeInsets这两个属性来设置具体的位置,另一种是我们直接封装一个imageView和label 来在定义button。两种方法都可以,在Swift中使用扩展 UIButton 来设置 titleEdgeInsets、imageEdgeInsets 感觉更灵活更方便一些。

  • 直接上代码:

    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 = UIEdgeInsetsZero
          var labelEdgeInset = UIEdgeInsetsZero
          let imageWith = self.imageView?.frame.size.width
          let imageHeight = self.imageView?.frame.size.height
          if Double(UIDevice.currentDevice().systemVersion) >= 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)!
          }
          labelWidth = CGFloat(36)
          switch style {
          case .ButtonEdgeInsetsStyleTop:
              imageEdgeInset = UIEdgeInsetsMake(-labelHeight-space/2.0, 0, 0, -labelWidth)
              labelEdgeInset = UIEdgeInsetsMake(0, -imageWith!, -imageHeight!-space/2.0, 0)
          case .ButtonEdgeInsetsStyleLeft:
            imageEdgeInset = UIEdgeInsetsMake(0, -space/2.0, 0, space/2.0);
            labelEdgeInset = UIEdgeInsetsMake(0, space/2.0, 0, -space/2.0);
          case .ButtonEdgeInsetsStyleBottom:
              imageEdgeInset = UIEdgeInsetsMake(0, 0, -labelHeight-space/2.0, -labelWidth)
              labelEdgeInset = UIEdgeInsetsMake(-imageHeight!-space/2.0, -imageWith!, 0, 0)
          case .ButtonEdgeInsetsStyleRight:
              // To Do print("坐标是====\(labelWidth)=====\(space)")
              imageEdgeInset = UIEdgeInsetsMake(0, labelWidth+space/2.0, 0, -labelWidth-space/2.0)
              labelEdgeInset = UIEdgeInsetsMake(0, -imageWith!-space/2.0, 0, imageWith!+space/2.0)
          }
          self.titleEdgeInsets = labelEdgeInset
          self.imageEdgeInsets = imageEdgeInset
      }
    }
    
  • 如代码所示,我们通过枚举,来列出图片与文字可能出现的位置,这样就能在方法中根据具体情况来展示文字与图片的位置。至于第二种方法我们可以通过xib或者纯代码封装一个button,在这里就不介绍了。

推荐阅读更多精彩内容