【问题标题】:Swift UIButton With Icon and Text (not using edgeinsets)带有图标和文本的 Swift UIButton(不使用 edgeinsets)
【发布时间】:2017-11-09 06:26:50
【问题描述】:

我正在尝试在某些文本的左侧获取一个带有图标的按钮:

我对 UIButton 的理解有问题。为按钮添加标题效果很好:

import UIKit

let button = UIButton(frame: CGRect(x: 0, y: 0, width: 300, height: 25))
button.backgroundColor = .green
button.contentHorizontalAlignment = .left
button.contentVerticalAlignment = .fill
button.titleLabel!.backgroundColor = .blue
button.setTitle("639", for: .normal)
button.setTitleColor(.white, for: .normal)

但是当你添加图片时

button.setImage(UIImage(named: "test"), for: .normal)
button.imageView!.backgroundColor = .clear
button.imageView!.contentMode = .scaleAspectFit

它保持原来的大小(300 像素)并将标题从右侧推出按钮边界。 (在屏幕截图中看不到它,因为它只显示按钮框架)

我做错了什么?为什么图像即使按比例缩小也保留其原始宽度? contentHorizontalAlignment 即使允许项目被推出框架,它还能做什么?

我知道您可以设置插图,但这是在可重复使用的视图中使用,因此我无法对值进行硬编码。

感谢您的帮助

【问题讨论】:

  • 你到底想要什么?我不明白。分享一张你期待的照片
  • @elk_cloner 用我正在拍摄的照片更新了操作
  • 我刚刚为您提供了解决方案。如果有帮助,希望您能接受我的回答。 :)
  • > 我知道您可以设置插图,但这是在可重复使用的视图中使用,因此我无法对值进行硬编码

标签: ios swift xcode8


【解决方案1】:

我只是按照你说的做了一个按钮。

顺便说一句,为什么不使用 inset。Apple 给了我们使用 this 的机会。那我们为什么不使用 this?

注意:您必须反复试验才能正确定位图像和文本。

自动布局:

和插图:

如果它不准确,我说你必须反复试验。快乐编码。 :)

【讨论】:

    猜你喜欢
    • 2015-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-15
    • 2011-06-23
    • 1970-01-01
    • 1970-01-01
    • 2021-04-22
    相关资源
    最近更新 更多