【问题标题】:How to add an image in the middle of UIButton title text?如何在 UIButton 标题文本中间添加图像?
【发布时间】:2019-02-09 20:35:22
【问题描述】:

我想达到以下设计:https://i.stack.imgur.com/D5kN3.png

如何在按钮文本中间设置图像/图标?

【问题讨论】:

标签: ios swift uibutton


【解决方案1】:

您可以为此使用属性字符串:

// create a NSMutableAttributedString with the text before the image
let beginning = NSMutableAttributedString(string: "Beginning")

// create a NSTextAttachment with the image
let imageAttachment = NSTextAttachment()
imageAttachment.image = UIImage(named: "image.png")

// create an NSMutableAttributedString with the image
let imageString = NSAttributedString(attachment: imageAttachment)

// add the image to the string
beginning.append(imageString)

// create an NSMutableAttributedString with the text after the image
let end = NSAttributedString(string: "End")
beginning.append()

// set the attributed text of the label
label.attributedText = beginning

【讨论】:

    【解决方案2】:

    您可以使用背景图片并左右设置标签。或者您可以创建一个新的 xib 视图,并根据需要扩展 UIButton 并使用它

    【讨论】:

      【解决方案3】:

      我在这里看到 2 个可能的选项:

      1. 在图片附件中使用属性字符串
      2. 使用带有 2 个标签和内部图像的 UIView,并在其上添加点击手势识别器。

      【讨论】:

        猜你喜欢
        • 2020-10-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-09-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多