2017-05-31 52 views
0

我是swift编码的新手,当我试图通过代码添加按钮时,它不会显示在模拟器中。按钮未显示swift

我将main.storyboard中视图的尺寸更改为375 * 1114 有滚动视图和内部视图,并且具有相同的尺寸。 也有5个集合视图。 这些都是由故事板设置的。

的代码我使用:

let fullScreenSize = UIScreen.main.bounds.size 
    let plusButton = UIButton(type: .custom) 
    plusButton.frame = CGRect(x: 300, y: 600, width: 50, height: 50) 
    plusButton.layer.cornerRadius = 0.5 * plusButton.bounds.size.width 
    plusButton.clipsToBounds = true 
    plusButton.setImage(UIImage(named: "plus.png"), for: .normal) 
    plusButton.center = CGPoint(x: fullScreenSize.width * 0.9, y: fullScreenSize.height * 0.9) 
    plusButton.addTarget(self, action: #selector(plusButtonPressed), for: .touchUpInside) 
    self.view.addSubview(plusButton) 

我试图让按钮留在模拟器的右下角所有的时间。我怎样才能做到这一点?谢谢。

+0

添加按钮作为ScrollView视图的子视图! –

+1

尝试'self.view.bringSubview(toFront:plusButton)' –

+1

在调试器中运行应用程序,然后点击“查看调试器”按钮(参见WWDC 2016 [可视化调试与Xcode](https://developer.apple .com/videos/play/wwdc2016/410 /)约5分钟)。然后你可以找出它的位置,从那里你应该能够轻松地调试问题。 – Rob

回答

0

你的代码是好的,正确添加背景颜色和检查一次该按钮将别人看得到检查plusButton.setImage(UIImage(named: "plus.png"), for: .normal)plus.png正确与否

plusButton.backgroundColor = UIColor.red 

全码

let fullScreenSize = UIScreen.main.bounds.size 
    let plusButton = UIButton(type: .custom) 
    plusButton.frame = CGRect(x: 300, y: 600, width: 50, height: 50) 
    plusButton.layer.cornerRadius = 0.5 * plusButton.bounds.size.width 
    plusButton.clipsToBounds = true 
    plusButton.setImage(UIImage(named: "normal.jpg"), for: .normal) 
    plusButton.backgroundColor = UIColor.red 
    plusButton.center = CGPoint(x: fullScreenSize.width * 0.9, y: fullScreenSize.height * 0.9) 
    // plusButton.addTarget(self, action: #selector(plusButtonPressed), for: .touchUpInside) 
    self.view.addSubview(plusButton) 

输出 enter image description here

+1

我想你需要将按钮添加到滚动视图的子视图(UIView),而不是self.view。 –

+0

我该怎么做这个过程?谢谢。 – szeto1121

+0

@ szeto1121 - pardon –

0

我想你必须在UIScrollview内部有一个UIView的插座,你已经拥有你UIViewController并将该按钮添加为该的那个UIView。这就是为什么你的按钮被隐藏起来,为什么不通过查看层次结构来检查它?

enter image description here

+0

如何将代码创建的按钮添加到View Hierarchy?谢谢。 – szeto1121

+0

如果添加了任何UIElement的子视图,它将自动添加到View Hierarchy层。你有没有把UIView的Outlet放进你的UIScrollView? –