简体   繁体   English

在新的Swift视图控制器文件上添加按钮不起作用

[英]Adding a button on a new Swift view controller file doesn't work

I am currently working on a game and want to add a pause button to it. 我目前正在开发游戏,想在游戏中添加暂停按钮。 One of my files is so large that it has become very slow and laggy. 我的一个文件太大,以至于变得非常缓慢和缓慢。 I'm trying to break up the code into separate files. 我正在尝试将代码分解为单独的文件。 I made a file named PauseScreen.swift and tried to make the pause button there, but it seems the code never ran. 我制作了一个名为PauseScreen.swift的文件,并尝试在其中制作暂停按钮,但是似乎代码从未运行过。 This is what I did: 这是我所做的:

    import Foundation
    import SpriteKit

    var pauseButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton

    class Pause: UIViewController {

        override func viewDidLoad() {

            let pauseButtonImage = UIImage(named: "Pause")
            pauseButton.setBackgroundImage(pauseButtonImage, forState: .Normal)
            pauseButton.frame = CGRectMake(self.view!.frame.width / 2 + 190, self.view!.frame.height - 300, 50, 50)
            pauseButton.addTarget(self, action: "pauseButtonTapped:", forControlEvents: .TouchUpInside)
            pauseButton.alpha = 1.0
            self.view?.addSubview(pauseButton)

        }


func pauseButtonTapped(sender:UIButton!){}
}

Any ideas? 有任何想法吗?

In viewDidLoad, the frame of your view is probably CGRectZero. 在viewDidLoad中,视图的框架可能是CGRectZero。 Try printing the frame and seeing what you get. 尝试打印框架,然后看得到什么。 If that's the case, move your code to viewWillAppear. 如果是这种情况,请将您的代码移至viewWillAppear。

Also, be very careful hardcoding your button's frame. 另外,请务必对按钮的框架进行硬编码。 It could end up off the screen with constants like 300. I suggest using auto layout to alleviate those issues. 它最终可能会在屏幕上显示300之类的常量。我建议使用自动布局来缓解这些问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM