【问题标题】:Right-align UIButton imageView右对齐 UIButton imageView
【发布时间】:2020-08-30 18:28:14
【问题描述】:

我需要将按钮图像放在文本之后。根据我在 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) 更改文本时,尽管文本更长/更短,但图标仍保持在原来的位置(因此有时我在新的长文本顶部有图标)。我该如何解决这个问题?

【问题讨论】:

  • 检查了您的代码,似乎工作正常
  • 尝试输入很长的文本,图标移动到文本旁边,按钮有宽度限制吗?还是您重写了intrinsicSize 方法以返回错误值?

标签: ios swift uibutton autolayout uikit


【解决方案1】:

如果您只使用标准的 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

【讨论】:

    猜你喜欢
    • 2020-06-02
    • 1970-01-01
    • 1970-01-01
    • 2017-04-27
    • 1970-01-01
    • 2014-08-11
    • 2022-07-22
    • 1970-01-01
    • 2013-05-20
    相关资源
    最近更新 更多