【问题标题】:Possible to left align button text but right align background or button image?可以左对齐按钮文本但右对齐背景或按钮图像?
【发布时间】:2018-03-26 22:02:43
【问题描述】:

您好,我在 Storyboard 中创建了一个 UIButton,我想将标题左对齐但图像右对齐。到目前为止,我一直无法找到一种方法来做到这一点。我知道可以添加单独的 UIImage,但为了简化自动布局,我希望通过一个按钮完成所有操作。

在故事板或代码中是否有可能?提前感谢您的任何建议

【问题讨论】:

    标签: ios objective-c uibutton


    【解决方案1】:

    在子类中覆盖它:

    - (CGRect)titleRectForContentRect:(CGRect)contentRect;
    - (CGRect)imageRectForContentRect:(CGRect)contentRect;
    

    然后在故事板中使用这个子类

    【讨论】:

      【解决方案2】:

      我的UIButton 扩展方法,在 Swift 中。抱歉不是obj-c。我的项目现在几乎是Swift写的了。

      extension UIButton {
          // ## Usage
          // let btn: UIButton = //... UIButton
          //
          // ... configure `image` and `text` before calling following method. 
          // btn.myImageRightAligned()
          // Let image of `UIButton` aligned right. 
      
          public func myImageRightAligned(_ spacing: CGFloat = 2.0) {
              let button = self
              guard (button.imageView != nil && button.imageView?.image != nil) else {
                  return
              }
              guard (button.titleLabel != nil && button.titleLabel?.text != nil) else {
                  return
              }
              let imageSize = button.imageView!.image!.size
              let title = button.titleLabel!.text! as NSString
              let titleSize = title.size(attributes: [NSFontAttributeName: button.titleLabel!.font])
      
              button.titleEdgeInsets = UIEdgeInsets(top: 0.0, left: -(imageSize.width + spacing), bottom: 0.0, right: imageSize.width)
              button.imageEdgeInsets = UIEdgeInsets(top: 0.0, left:  titleSize.width, bottom: 0.0, right: -(titleSize.width + spacing))
      
              self.setNeedsLayout()
          }
      }
      

      【讨论】:

        【解决方案3】:

        您可以从情节提要中的元素检查器更改按钮图像偏移(更改位置),我不明白对齐背景的含义,因为它覆盖了整个按钮,其中没有左右

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-04-18
          • 1970-01-01
          • 1970-01-01
          • 2019-01-16
          • 2014-12-27
          • 2017-11-04
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多