Swift 3.0 – UIButton标签高度的高度为零

我正在添加一个简单的更新button到我的应用程序页面。 该button有一个imageView,应该有一个标题“立即更新”在视图的顶部。

在视图层次结构中,我可以看到UILabel作为UIButton的子视图。 但是打印UILabel的描述返回帧

(250 20; 283 0). 

这是我的代码

 let updateButton = UIButton() updateButton.frame = CGRect(x: centreX(parent: self.view, width: 150), y: 200, width: 150, height: 40) updateButton.setImage(UIImage(named:"my-image"), for: .normal) updateButton.setTitle("Update Now", for: .normal) updateButton.titleLabel?.sizeToFit() updateButton.titleLabel?.frame = updateButton.frame updateButton.setTitleColor(UIColor.black, for: .normal) self.view.addSubview(updateButton) 

我想到了两条线

 updateButton.titleLabel?.sizeToFit() updateButton.titleLabel?.frame = updateButton.frame 

会改变标签框架的高度。 有什么我在这里失踪?

使用Swift 3.0和iOS 10

我认为你需要设置背景图像,而不是像下面的图像

 updateButton.setBackgroundImage(UIImage(named: "my-image"), for: .normal) 

我发现这个问题。 从UIButton文档

提供一个标题string或图像; 为您的内容适当调整button大小。

这意味着这些属性中只有一个可以设置。 当我首先设置图像时,这就是所显示的内容。 这是我看不到标签的原因。

当我解决问题时,我有两个解决scheme:

首先 – 使用标题并设置背景颜色

 updateButton.setTitle("Update Now", for: .normal) updateButton.setTitleColor(UIColor.white, for: .normal) updateButton.backgroundColor = UIColor(patternImage: UIImage(named: "my-image")!) 

这是我用的。 我不得不缩放背景图像,以适应视图。

另外 – 结合立即更新文本创build一个新的图像

 updateButton.setImage(UIImage(named:"my-new-image"), for: .normal) 

我希望这可以帮助别人。