ios-左对齐图像并将文本放置在按钮的中心

ios-左对齐图像并将文本放置在按钮的中心,ios,swift,uibutton,text-alignment,Ios,Swift,Uibutton,Text Alignment,我一直在尝试对齐按钮左侧的图像,同时在按钮中心放置一些文本。我一直在关注此堆栈溢出帖子: 我遵循其中一个对我最有效的答案。下面是答案的代码: @IBDesignable class LeftAlignedButton: UIButton { override func layoutSubviews() { super.layoutSubviews() if let image = imageView?.image { let m

我一直在尝试对齐按钮左侧的图像,同时在按钮中心放置一些文本。我一直在关注此堆栈溢出帖子:

我遵循其中一个对我最有效的答案。下面是答案的代码:

@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)
        }

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

以下是我当前的按钮的外观:

正如你可能在谷歌按钮中看到的文本一样,尽管该按钮的居中位置与facebook按钮的文本居中位置不一致。另外,图像有点太大了,但我不知道如何使它们变小

以下是我正在寻找的结果:


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

@Rohan问题是
让margin=30-image.size.width/2
。您正在使用图像宽度来查找边距。图像(
facebook和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()