Use swift to display the rounded uibutton button in Sprite

Source: Internet
Author: User

I am not very familiar with objective-C, and I have never used uikit before. spritekit only read the tutorials and then read the swift language tutorials. At this time, I started to write this program, therefore, the problem is solved by pediatrics, and the solution is also a curve to save the country. I hope someone can give me some advice on a simple way to solve these problems. After a good solution is available, I will modify this log at any time, to avoid misleading others.

The program interface is very simple

Then, click the game area in the middle to roll back and randomly generate 1 ~ The number 6 indicates several steps before the plane goes forward. When it encounters a ladder, it jumps forward several steps. when it encounters a snake, it moves back several steps to guide the plane to the 25 level and the game ends.

There is a tag above that shows the game status and roll point value.

There is a restart button below to restart the game. The key to this log is this button.

At first, I thought it was easy to add a button in Sprite's scene, but in spritekit, I didn't find a button control or something. I started to use label to replace the button function, it is to judge the control in the click event and then execute the Code related to the button. This method is too ugly, and the other is that there is no button action when the button is clicked, third, the call of the button method is too difficult.

Later I found uibutton. I refer to the following objective-C code for adding buttons:

Cgrect frame = cgrectmake (90,200,200, 60); uibutton * someaddbutton = [uibutton buttonwithtype: uibuttontyperoundedrect]; someaddbutton. backgroundcolor = [uicolor clearcolor]; [someaddbutton settitle: @ "add a button dynamically! "Forstate: uicontrolstatenormal]; someaddbutton. Frame = frame; [someaddbutton addtarget: Self action: @ selector (somebuttonclicked) forcontrolevents: role]; [self. View addsubview: role];

First, you must read an official Apple document, using SWIFT with cocoa and objective-C.

How to modify the OC code to SWIFT, according to the above Code and instructions, the second line should be changed

var someAddButton = UIButton.buttonWithType(.RoundedRect) as UIButton

Press and hold the command key and click the buttonwithtype function. You can see that this is a type function and returns anyobject! Because uibuttontype does not have the rounded rectangle

enum UIButtonType : Int {    case Custom // no button type    case System // standard system button        case DetailDisclosure    case InfoLight    case InfoDark    case ContactAdd}

Let me discard this rounded rectangle and use a normal button.

        var btn  = UIButton()        btn.setTitle("RESTART",forState: .Normal)                btn.frame = CGRect(x:screen.bounds.size.width/2-50, y:screen.bounds.size.height-100,width:100,height:50)                self.addChild(btn)        //self.view.addSubview(btn)

The problem arises again. BTN is not a sknode at all and cannot be added. Looking at the OC example, it is obvious that BTN is added to the view, so it is changed to the comment sentence, however, no buttons are displayed after running. How can this be done.

So I started searching for information and finally found another example of Apple code: uicatalog: Creating and customizing uikit controls in swift. This sample code is not running after I download it, however, examples of various controls are certainly correct. uibutton is added to viewcontroller. In my project, there are three swift files, one of which is gameviewcontroller. swift, I can see the code in it and understand that gamescene is added to this display, so the button should also be added here.

Therefore, write the code for adding a button in the viewdidload method of gameviewcontroller:

    var btn:UIButton = UIButton()    var gameScene:GameScene?    override func viewDidLoad() {        super.viewDidLoad()        if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene {            // Configure the view.            let skView = self.view as SKView            skView.showsFPS = true            skView.showsNodeCount = true                        /* Sprite Kit applies additional optimizations to improve rendering performance */            skView.ignoresSiblingOrder = true                        /* Set the scale mode to scale to fit the window */            scene.scaleMode = .AspectFill            skView.presentScene(scene)                        var screen = UIScreen.mainScreen()            println("screen width:\(screen.bounds.size.width),height:\(screen.bounds.size.height)")            btn.setTitle("RESTART",forState: .Normal)            btn.backgroundColor = UIColor.redColor()            btn.frame = CGRect(x:screen.bounds.size.width/2-50, y:screen.bounds.size.height-100,width:100,height:50)                        skView.addSubview(btn)            gameScene = scene        }    }

After the button is added, it is very ugly. I tried the button type and none of them can be used.

First, there is no rounded rectangle, and second, there is no raised button.

I also read several uibutton methods and found that I can set the background image and button text at the same time, so I can not get a button image, to create a button for the rounded rectangle.

So I made the following button image:

Note: This image is preferably in PNG format. The Orange area is the entire image and there is no white background. I use the smart cable Cutting feature of image preview provided by Apple.

Use the following code to start with a cost log:

class GameViewController: UIViewController {    var btn:UIButton = UIButton()    var gameScene:GameScene?    override func viewDidLoad() {        super.viewDidLoad()        if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene {            // Configure the view.            let skView = self.view as SKView            skView.showsFPS = true            skView.showsNodeCount = true                        /* Sprite Kit applies additional optimizations to improve rendering performance */            skView.ignoresSiblingOrder = true                        /* Set the scale mode to scale to fit the window */            scene.scaleMode = .AspectFill            skView.presentScene(scene)                        var screen = UIScreen.mainScreen()            println("screen width:\(screen.bounds.size.width),height:\(screen.bounds.size.height)")                        let buttonTitle = NSLocalizedString("RESTART", comment: "you will restart the game")            btn.setTitle(buttonTitle,forState: .Normal)                        var image = UIImage(named:"button")            btn.setBackgroundImage(image,forState: .Normal)                        btn.frame = CGRect(x:screen.bounds.size.width/2-50, y:screen.bounds.size.height-100,width:100,height:50)                        btn.addTarget(self, action: "buttonClicked:", forControlEvents: .TouchUpInside)            skView.addSubview(btn)            gameScene = scene        }    }    func buttonClicked(sender: UIButton) {        print("A button was clicked: \(sender).")        if let scene = gameScene? {            println("board width:\(scene.spriteBoard.size.width),height:\(scene.spriteBoard.size.height)")            var alert = scene.gameRestartAsk()            presentViewController(alert, animated: true, completion: nil)        }    }}

I am a beginner in IOS. Please kindly advise. Thank you.




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.