【问题标题】:Getting strange result while trying to create UIButton with image and text尝试使用图像和文本创建 UIButton 时得到奇怪的结果
【发布时间】:2017-01-02 17:25:45
【问题描述】:

我正在尝试创建一个带有自定义UIButtonType 的UIButton,该UIButtonType 配置了左对齐的图像和居中的文本。但是,我能找到的每个示例(有很多)都不起作用并产生了一些奇怪的结果。 我使用的代码:

let button = UIButton(type: UIButtonType.custom)
button.frame = CGRect(x: 50, y: 50, width: 100, height: 100)
button.addTarget(self, action: #selector(StartController.button), for: .touchUpInside)
button.setImage(UIImage(named: "IMG_0124"), for: .normal)
button.imageEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0)
button.setTitle("Back", for: .normal)
button.titleEdgeInsets = UIEdgeInsetsMake(0, 20, 0, 0)
button.contentHorizontalAlignment = .left

我在调试器中得到这个:

(lldb) po button.imageView?.frame
▿ Optional<CGRect>
  ▿ some : (10.0, 0.0, 90.0, 100.0)
    ▿ origin : (10.0, 0.0)
      - x : 10.0
      - y : 0.0
    ▿ size : (90.0, 100.0)
      - width : 90.0
      - height : 100.0


(lldb) po button.titleLabel?.frame
▿ Optional<CGRect>
  ▿ some : (100.0, 50.0, 2368.0, 0.0)
    ▿ origin : (100.0, 50.0)
      - x : 100.0
      - y : 50.0
    ▿ size : (2368.0, 0.0)
      - width : 2368.0
      - height : 0.0 

我无法通过button.imageView?.frame 设置框架。

这就是我想要得到的:

这是我得到的:

按钮不是 UINavigationController 的一部分。它是一个简单 UIView 的子视图。

知道有什么问题吗?

【问题讨论】:

  • 可能有几处错误,但在您告诉我们两件事之前很难说清楚。 (1) 你期待看到什么?另外,这应该是 UINavigationBar 的一部分吗?我问是因为“后退”的标题。 (2) 你在看什么?任何事物?帮助我们帮助您。

标签: ios swift image text uibutton


【解决方案1】:

迅速 3. 试试这个

button.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
button.titleLabel.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
button.imageView.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)`
button.imageEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)

【讨论】:

  • 对不起,这没有帮助
猜你喜欢
  • 1970-01-01
  • 2021-03-17
  • 1970-01-01
  • 1970-01-01
  • 2022-01-25
  • 2020-10-08
  • 1970-01-01
  • 2013-08-21
  • 1970-01-01
相关资源
最近更新 更多