如何将图像放在按钮的右侧,文本左对齐

时间:2014-11-23 23:48:34

标签: ios uibutton xcode6 imageedgeinsets

我有UIButton图片和文字。如何将图像对齐到右边,并将文本对齐到左边?

2 个答案:

答案 0 :(得分:0)

@IBDesignable class RightImageButton: UIButton {

    @IBInspectable var alignImageToRight: Bool = true

    override func layoutSubviews() {
        super.layoutSubviews()
        if alignImageToRight {
            if let imageView = self.imageView, let titleLabel = self.titleLabel {
                let imageWidth = imageView.frame.size.width
                var imageFrame: CGRect = imageView.frame;
                var labelFrame: CGRect = titleLabel.frame;
                labelFrame.origin.x = self.titleEdgeInsets.left + self.contentEdgeInsets.left
                imageFrame.origin.x = frame.width - self.imageEdgeInsets.right - self.contentEdgeInsets.right - imageWidth
                imageView.frame = imageFrame;
                titleLabel.frame = labelFrame;
            }
        }
    }

}

答案 1 :(得分:0)

使用以下两种方法

button.imageEdgeInsets = UIEdgeInsets(top: 0.0, left: 0, bottom: 0.0, right: 0.0)
button.titleEdgeInsets = UIEdgeInsets(top: 0.0, left: 0, bottom: 0.0, right: 0.0)

左右传递值并进行调整。 根据您的要求设置偏移量。