在程序化视图中,无法单击我的按钮

时间:2014-06-11 03:44:42

标签: uiview swift

我有一个UIView导致另一个UIView。我将userInteraction设置为true。我的按钮显示,但单击按钮时按钮不执行任何操作。我添加了一个println语句,以确保它不仅仅是我在函数中运行的代码。视图出现问题,或按钮和功能如何连接。

我正在使用Swift。

这是我的代码。它位于剪辑中,因此您将看不到viewDidLoad方法:

let initialLaunchController = UIView()
    let teachingScreen = UIView()

        learnToPlayButton.setTitle("Click here to learn how to play.", forState: .Normal)
        learnToPlayButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        learnToPlayButton.titleLabel.font = UIFont(name: "HelveticaNeue-UltraLight", size: 35)
        learnToPlayButton.titleLabel.textAlignment = .Center
        learnToPlayButton.addTarget(self, action: "LearnToPlayPage:", forControlEvents: .TouchUpInside)
        learnToPlayButton.frame = CGRectMake(37, 70, 500, 200)
 initialLaunchController.backgroundColor = UIColor.whiteColor()
        teachingScreen.backgroundColor = UIColor.whiteColor()

        initialLaunchController.userInteractionEnabled = true
        teachingScreen.userInteractionEnabled = true

    func LearnToPlayPage(sender: UIButton!) {
        //switch view to actually teach to learn to play

        println("debugging..")

        let imageViewInsideFunc = UIImageView(image: background)
        self.teachingScreen.addSubview(imageViewInsideFunc)
        self.teachingScreen.addSubview(titleToTeachToPlayLabel)
        self.teachingScreen.addSubview(teachToPlayLabel)
        self.teachingScreen.addSubview(sureGetStartedButton)
        self.initialLaunchController.addSubview(teachingScreen)

    }

2 个答案:

答案 0 :(得分:0)

您的addTarget方法调用(action: "LearnToPlayPage:")中确实有正确的参数,但该按钮无法在您的视图控制器子类上找到该方法,因为您已嵌套在在内部设置UIButton的方法。它需要被定义为子类的方法:

class ViewController: UIViewController {
    var learnToPlayButton = UIButton()

    override func viewDidLoad() {
        super.viewDidLoad()

        // set up views and button properties    
        learnToPlayButton.addTarget(self, action: "LearnToPlayPage:", forControlEvents: .TouchUpInside)
        // etc, etc
    }

    func LearnToPlayPage(sender: UIButton!) {
        // switch view to actually teach to learn to play
        println("found LearnToPlayPage(sender: UIButton!)")
    }
}

答案 1 :(得分:0)

您应该使用Selector初始化程序包装action参数:

learnToPlayButton.addTarget(self, action: Selector("LearnToPlayPage"), forControlEvents: UIControlEvents.TouchUpInside)