ios - 尝试使用图像和文本创建 UIButton 时出现奇怪的结果

标签 ios swift image text uibutton

我正在尝试创建一个带有自定义UIButtonTypeUIButton,该自定义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 设置框架。

这就是我想要得到的: enter image description here

这就是我得到的: enter image description here

该按钮不是 UINavigationController 的一部分。它是一个简单 UIView 的 subview 。

知道出了什么问题吗?

最佳答案

swift 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)

关于ios - 尝试使用图像和文本创建 UIButton 时出现奇怪的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41430913/

相关文章:

UINav 栏中未显示 Swift 后退按钮

ios - 在 Swift 中将可视格式语言与 iCarousel 结合使用

python - 为什么这个图像在 tkinter 中不显示?

ios - 在 segueing 之前按下另一个 TableViewCell 中的按钮时,在 TableViewCell 中捕获 TextView 值?

ios - 无效的可执行文件大小 - 来自 iTunes Connect

ios - "Push Notifications"目标能力和解析推送

swift - 使用自定义 NSTextBlock 保存和粘贴属性字符串

javascript - CSS:如何从 Javascript 变量设置以中间为原点的元素位置?

PHP MySQL 无法从数据库中找到我的图像

iOS:使用 AudioUnitRender 的模拟器中存在错误