UIButton 未使用 Swift 在 UIView 中显示

Posted

技术标签:

【中文标题】UIButton 未使用 Swift 在 UIView 中显示【英文标题】:UIButton not showing in UIView using Swift 【发布时间】:2014-11-06 15:25:13 【问题描述】:

我正在尝试创建一个位于屏幕底部的视图。 UIView 正常工作并显示。我试图在其中放置一个 UIView 大小的 UIButton,但该按钮不会显示。我把这段代码放在了 Swift Playground 中,它成功了!当我在我的应用程序的 ios 模拟器中运行它时,UIView 显示但不显示按钮。我不知道发生了什么。

var ySize = UIScreen.mainScreen().bounds.size.height - 40
let searchView = UIView(frame: CGRect(x: 0, y: ySize, width: self.view.bounds.width, height: 40))
searchView.backgroundColor = UIColor(red: 0/255.0, green: 71/255.0, blue: 133/255.0, alpha: 1)

let searchButton: UIButton = UIButton.buttonWithType(.System) as UIButton
searchButton.frame = searchView.frame
searchButton.tintColor = UIColor.whiteColor()
searchButton.setTitle("Search Transactions", forState: .Normal)

searchView.addSubview(searchButton)

self.navigationController?.view.addSubview(searchView)

【问题讨论】:

尝试使用searchButtoncenter 属性看看。我猜你的按钮不在屏幕上。 我只是累了,还是没有运气。如果我添加一个 UILabel 它可以工作。只是按钮不起作用。我很困惑! 【参考方案1】:

我明白了。我使用的是框架而不是边界。使用框架会错误地放置它,但使用边界使其工作。

searchButton.frame = CGRectMake(0, 0, recentView.bounds.width, recentView.bounds.height)

【讨论】:

正是我要到达的地方 ;-) 很高兴它成功了。【参考方案2】:

Swift 3.x+

searchButton.frame = CGRect.init(x: 0.0, y:0.0, width:200.0, height:50.0)

【讨论】:

以上是关于UIButton 未使用 Swift 在 UIView 中显示的主要内容,如果未能解决你的问题,请参考以下文章

Swift 中选中/未选中的 UIButton

Swift:在自定义视图中未调用 UIButton 触摸事件

Swift UIButton 子类未显示在设备或模拟器上

Swift - 无论状态如何设置 UIButton 标题

Swift - CABasicAnimation 完成时更新 UIButton

调用UIButton.isHidden = true / false时,视图未更新