ios - 左对齐图像并将文本置于 UIButton 的中心

ios - Left Align Image and Place Text in Center of UIButton

我一直在尝试在按钮左侧对齐图像,同时在按钮中央放置一些文本。我一直在关注这个堆栈溢出 post: Left-align image and center text on UIButton.

我遵循了最适合我的答案之一。这是该答案的代码:

@IBDesignable class LeftAlignedButton: UIButton {
    override func layoutSubviews() {
        super.layoutSubviews()

        if let image = imageView?.image {

            let margin = 30 - image.size.width / 2
            let titleRec = titleRect(forContentRect: bounds)
            let titleOffset = (bounds.width - titleRec.width - image.size.width - margin) / 2


            contentHorizontalAlignment = UIControlContentHorizontalAlignment.left
            imageEdgeInsets = UIEdgeInsetsMake(0, margin, 0, 0)
            titleEdgeInsets = UIEdgeInsetsMake(0, titleOffset, 0, 0)
        }

    }
} 

尽管这让我非常接近我想要的结果,但它并没有完全实现我想要的。

这是我当前按钮的样子:

您可能会看到 google 按钮中的文本,即使该特定按钮的居中与 facebook 按钮文本的居中方式不一致。另外,图片有点大,不知道怎么缩小。

这是我要查找的结果:

总而言之,我的问题是如何正确地将 google 按钮的文本居中,使其与 facebook 按钮的设计相对应,以及如何缩小图像。

@Rohan 问题是let margin = 30 - image.size.width / 2。您正在使用图像宽度来找出 margin.The 图像 (facebook and google) 大小不同(我假设)。因此,根据您的代码,标签左边距必须随图像宽度而变化。所以如果你想实现你必须根据你的代码保持两个图像大小相似。

你也可以试试这个。适用于不同的图像宽度和不同的标题。

extension UIButton {
    func moveImageLeftTextCenter(imagePadding: CGFloat = 30.0){
        guard let imageViewWidth = self.imageView?.frame.width else{return}
        guard let titleLabelWidth = self.titleLabel?.intrinsicContentSize.width else{return}
        self.contentHorizontalAlignment = .left
        imageEdgeInsets = UIEdgeInsets(top: 0.0, left: imagePadding - imageViewWidth / 2, bottom: 0.0, right: 0.0)
        titleEdgeInsets = UIEdgeInsets(top: 0.0, left: (bounds.width - titleLabelWidth) / 2 - imageViewWidth, bottom: 0.0, right: 0.0)
    }
}

用法:myButton.moveImageLeftTextCenter()