在 UIButton 上左对齐图像并居中文本

79

我看到了有关右对齐的帖子,但我无法让左对齐起作用。 我希望按钮占据屏幕的宽度,图像位于左侧,标题/文本位于中心。

以下代码不起作用(至少不可靠):

    button.titleLabel.textAlignment = UITextAlignmentCenter;
    [button setImageEdgeInsets:UIEdgeInsetsMake(0, -60.0, 0, 0)];
    button.frame = CGRectMake((self.view.frame.size.width - w ) / 2, self.view.frame.size.height - 140.0,  self.view.frame.size.width - 10.0, 40.0);
27个回答

1
@trishcode的答案对我有用。我只是在使用UIButton的扩展来实现它。
以下是代码:
extension UIButton {
func centerImageLeft(padding: CGFloat = 30.0){
    let buttonWidth = self.frame.width
    let textWidth = self.titleLabel?.intrinsicContentSize.width ?? 0
    let imageViewWidth = self.imageView?.frame.size.width ?? 0
    let offsetToLeftButtonEdge = buttonWidth - textWidth - imageViewWidth
    let offset = offsetToLeftButtonEdge - padding
    self.imageEdgeInsets = UIEdgeInsets(top: 0.0, left: 0, bottom: 0.0, right: offset)
}
}

在viewDidAppear方法中,您可以这样调用它:
button.centerImageLeft()

1
你可以忘记UIEdgeInsets,只需在你的UIButton子类中在layoutSubviews()中重写框架即可。
要居中titleLabel,只需将水平偏移量添加到titleLabel框架中,该偏移量为super.bounds.midX和titleLabel.frame.midX之间的差异。
   override func layoutSubviews() {
       super.layoutSubviews()
       
       if let label = titleLabel {
           label.frame = label.frame.offsetBy(dx: super.bounds.midX - 
                label.frame.midX , dy: 0)
       }

       // Available space to the left of the titleLabel is simply:
       let leftAvailableWidth = label.frame.minX

       imageView?.frame = CGRect(x: 0, y: 0, width: <Some width smaller than leftAvailableWidth>, height: super.bound.height)
   }

1

Swift版本:

var button = UIButton()

newGameButton.setTitle("Новая игра", for: .normal)
newGameButton.setImage(UIImage(named: "energi"), for: .normal)
newGameButton.backgroundColor = .blue
newGameButton.imageEdgeInsets.left = -50

enter image description here


0

SWIFT 5+

也许最简单、最美观的变体是使用UIButton.Configuration

private func bottomButtonsConfiguration() -> UIButton.Configuration {
  var config: UIButton.Configuration = .filled()
  config.background.backgroundColor = Asset.Colors.cellsBackground.color
  config.baseForegroundColor = Asset.Colors.textColorOnLight.color
  config.cornerStyle = .small
  config.imagePadding = 14
  config.imagePlacement = .top
  config.imageColorTransformer = UIConfigurationColorTransformer { _ in
    return Asset.Colors.primaryColor.color
  }
  config.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { attribute in
    var muttableAttribute = attribute
    muttableAttribute.font = self.theme.font(style: .medium, size: 16)
    return muttableAttribute
  }

  return config
}

您的问题的解决方案是 config.imagePlacement = .top

预期结果图片


0

对于不同的按钮文本大小,这对我很有效。

获取准确的按钮文本宽度的关键是获得intrinsicContentSize。由于我正在使用自动布局来设置按钮宽度,所以我必须在viewDidAppear中运行此代码,而不是在viewDidLoad中运行,以便按钮已经被绘制,因此按钮框架大小将是准确的。

private func calculateAccountButtonImageViewOffset(button: UIButton, padding: CGFloat = 30.0) -> CGFloat {
    let buttonWidth = button.frame.width
    let textWidth = button.titleLabel?.intrinsicContentSize.width ?? 0
    let imageViewWidth = button.imageView?.frame.size.width ?? 0
    let offsetToLeftButtonEdge = buttonWidth - textWidth - imageViewWidth
    return offsetToLeftButtonEdge - padding
}

使用方法:

let imageViewOffset = calculateAccountButtonImageViewOffset(button: button)
button.imageEdgeInsets = UIEdgeInsets(top: 0.0, left: 0, bottom: 0.0, right: imageViewOffset)

按钮标题可以通过IB上的标题插图进行偏移,以达到所需效果: enter image description here

0

Swift 5: 你可以通过使用自定义的UIButton类来实现这一点。

class CustomButton: UIButton {

    var imageV = UIImageView()
    var titleV = UILabel()

    override func awakeFromNib() {

        self.imageView?.isHidden = true
        self.titleLabel?.isHidden = true

        imageV.frame = CGRect(x: 0, y: 0, width: 40, height: self.bounds.height)
        imageV.contentMode = .scaleAspectFit

        titleV.frame = CGRect(x: 40, y: 0, width: self.bounds.width - 40, height: self.bounds.height)
        titleV.font = self.titleLabel?.font
        titleV.textAlignment = .center

        self.addSubview(imageV)
        self.addSubview(titleV)

        imageV.image = self.imageView?.image; titleV.text = self.titleLabel?.text

        imageV.translatesAutoresizingMaskIntoConstraints = false
        imageV.topAnchor.constraint(equalTo: self.topAnchor, constant: 0).isActive = true
        imageV.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0).isActive = true
        imageV.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 0).isActive = true
        imageV.trailingAnchor.constraint(equalTo: titleV.leadingAnchor, constant: 0).isActive = true
        imageV.widthAnchor.constraint(equalToConstant: 40).isActive = true

        titleV.translatesAutoresizingMaskIntoConstraints = false
        titleV.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
        titleV.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
        titleV.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: 0).isActive = true
    }
}

之后您可以像这样设置图像和文本。

button.imageV.image = myImage
button.titleV.text = myText

结果

enter image description here


-2
最好创建一个自定义的UIButton子类来更好地解决这些问题。苹果可能正在“重置”您的设置。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接