将目标添加到UIButton以进行superview

时间:2015-10-16 15:04:38

标签: ios swift uiview uibutton skscene

我正在以cyl编程方式添加UIView。在这个SKScene中,我有一个按钮,可以在UIView中触发命令。我该怎么做呢?我的代码抛出异常。或者这可能只是不干净的编程?

SKScene

似乎我搞砸了class LevelAchievedView: UIView { override init(frame: CGRect) { super.init(frame: frame) self.opaque = false } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func drawRect(rect: CGRect) { let replayButton = UIButton() replayButton.setTitle("Replay?", forState: UIControlState.Normal) replayButton.setTitleColor(UIColor.greenColor(), forState: UIControlState.Normal) replayButton.titleLabel!.font = UIFont(name: "HelveticaNeue-Light", size: 30) replayButton.addTarget(self.superview, action: "returnToStart", forControlEvents: .TouchUpInside) replayButton.frame.origin = CGPointMake(10, 10) self.addSubview(replayButton) } ,我想在这种情况下我不能使用self.superview,尽管我在SKScene中有replayButton.addTarget(self.superview...。我错过了什么?

引发的异常:

func returnToStart()

2 个答案:

答案 0 :(得分:0)

您需要实现returnToStart。尝试添加以下内容:

function returnToStart() {
    println("returning to start");
}

到您的LevelAchevedView班级

答案 1 :(得分:0)

self.superview不是SKScene。只是一个解决方案:

class LevelAchievedView: UIView {
    let replayButton: UIButton

    override init(frame: CGRect) {
        self.replayButton = UIButton()

        super.init(frame: frame)
        self.opaque = false

        replayButton.setTitle("Replay?", forState: UIControlState.Normal)
        replayButton.setTitleColor(UIColor.greenColor(), forState: UIControlState.Normal)
        replayButton.titleLabel!.font = UIFont(name: "HelveticaNeue-Light", size: 30)
        replayButton.frame.origin = CGPointMake(10, 10)
        self.addSubview(replayButton)
    }
}

class MyScene: SKScene {
    override func didMoveToView(view: SKView) {
        // ...
        let levelAchieved = LevelAchievedView(rect: CGRect(...))
        levelAchieved.replayButton.addTarget(self, action: "returnToStart", forControlEvents: .TouchUpInside)
        view.addSubview(levelAchieved)
    }

    func returnToStart() {
        // your code here
    }
}