我一直试图在一个按钮的左边对齐一个图像,同时也在一个按钮的中央放置一些文本。我一直在跟踪这个堆栈溢出帖子: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按钮的设计相对应,以及如何使图像变小。
发布于 2017-02-25 19:39:58
@Rohan这个问题是let margin = 30 - image.size.width / 2。您正在使用图像宽度来找出margin.The图像(facebook and google)大小是不同的(我假设)。因此,根据您的代码,标签左边框必须随着图像宽度的变化而变化。因此,如果您想要实现,您必须保持两个图像大小相似,根据您的代码。
发布于 2018-03-26 19:30:58
你也可以试试这个。适用于不同的图像宽度和不同的标题。
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()
https://stackoverflow.com/questions/42459883
复制相似问题