UIButton的位置无法正确显示

时间:2015-12-31 16:26:54

标签: ios swift uibutton

我正在处理Swift中的按钮。好吧,似乎Swift没有正确设置我的UIButton的位置,因为它在屏幕上显示,当我想要它在中心时。这是我的代码,我做错了吗?

import SpriteKit
import UIKit

class GameScene: SKScene, SKPhysicsContactDelegate {
override func didMoveToView(view: SKView) {
    /* Setup your scene here */

    let button = UIButton(type: UIButtonType.System)

    let buttonImage = UIImage(named: "Button")
    button.frame = CGRectMake(self.frame.size.width / 2, self.frame.size.height / 2, 100, 86) // x, y, width, height
    button.setBackgroundImage(buttonImage, forState: UIControlState.Normal)
    button.addTarget(self, action: "buttonAction", forControlEvents: UIControlEvents.TouchUpInside)
    self.view?.addSubview(button)

}

func buttonAction (sender: UIButton!) {

    print("Button tapped")

}

请帮忙:/

1 个答案:

答案 0 :(得分:1)

尝试这可能有所帮助。

import SpriteKit
import UIKit

class GameScene: SKScene, SKPhysicsContactDelegate {
override func didMoveToView(view: SKView) {
    /* Setup your scene here */

    let button = UIButton()

    let buttonImage = UIImage(named: "Button")

    button.frame.size = CGSizeMake(100, 86)
    button.center = self.view.center;
    button.setBackgroundImage(buttonImage, forState: UIControlState.Normal)
    button.addTarget(self, action: "buttonAction", forControlEvents: UIControlEvents.TouchUpInside)
    self.view?.addSubview(button)

}