我正在尝试创建一个带有自定义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 的 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/