右对齐UIButton imageView

问题描述 投票:0回答:1

我需要把按钮图片放在文字后面。按照我在SoF上找到的一些答案,我将UIButton子类化,如下图所示。

class RightAlignedIconButton: UIButton {
    override func titleRect(forContentRect contentRect: CGRect) -> CGRect {
        var frame = super.titleRect(forContentRect: contentRect)
        frame.origin.x = titleEdgeInsets.left

        return frame
    }

    override func imageRect(forContentRect contentRect: CGRect) -> CGRect {
        let titleRectangle = titleRect(forContentRect: contentRect)

        var frame = super.imageRect(forContentRect: contentRect)
        frame.origin.x = titleRectangle.origin.x + titleRectangle.width + imageEdgeInsets.left

        return frame
    }
}

我遇到的问题是,当我改变文字时 acceptanceStatusButton.setTitle("New text", for: .normal) 尽管文本变长变短,但图标仍然保留在原来的位置(所以有时我的图标就在新的长文本的顶部)。我怎样才能解决这个问题?

ios swift uibutton autolayout uikit
1个回答
0
投票

如果你只是使用标准的setTitle和setImage,它将自动包含标题右边的图片。你不需要一个自定义的子类。

//Set button's image
let image = UIImage(systemName: "heart.fill") //Your image here
button.setImage(image, for: .normal)

//Optional: Remove background image if you added one on accident
button.setBackgroundImage(nil, for: .normal)

//Optional: Set button's title (displayed next to button's image)
button.setTitle(nil, for: .normal)

//The button's "content" includes the title label and image
//So we can set the button's content to fill the button
//If title label is nil, the content will only show the image
button.contentVerticalAlignment = .fill //optional
button.contentHorizontalAlignment = .fill //optional

//Set button's image to desired content mode (aspectFit avoids distortion)
//This restricts the image from resizing to fill the entire content area
button.imageView?.contentMode = .scaleAspectFit
© www.soinside.com 2019 - 2024. All rights reserved.