UISwitch:Swift 3:以编程方式 [英] UISwitch: Swift 3: Programmatically

查看:103
本文介绍了UISwitch:Swift 3:以编程方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何以编程方式添加一个uiswitch并在打开时调用一个动作,而在关闭时调用一个动作?香港专业教育学院一直在寻找小时.我可以帮忙吗?我知道如何添加开关,但是无论我处于什么场景,它都将保留在屏幕上.到目前为止,我已经能够添加按钮并将其从打开切换为关闭,但是由于某种原因,该开关只是在每个场景的屏幕上都显示.在那之后我迷路了,所以我遵循了这一点.来自如何以编程方式将UISwitch放置在SpriteKit/Skcene中

How can I programmatically add a uiswitch and call an action when on and one when off? Ive been searching for hours now. Can I please have some help? I know how to add the switch but it stays on the screen no matter what scene I'm on. So far, I've been able to add the button and make it switch from on to off, but for some reason the switch just says on the screen in every scene. I was lost after that so I followed this; from How to programmatically put a UISwitch in a SpriteKit/Skcene

是的,有可能.只需在您的SKScene类中使用以下代码:

Yes it is possible. Just use this code in your SKScene class:

override func didMoveToView(view: SKView) {
    /* Setup your scene here */
    let switchDemo = UISwitch(frame:CGRectMake(150, 300, 0, 0))
    switchDemo.on = true
    switchDemo.setOn(true, animated: false)
    switchDemo.addTarget(self, action: "switchValueDidChange:", forControlEvents: .ValueChanged)
    self.view!.addSubview(switchDemo)
}

Helper方法:

func switchValueDidChange(sender:UISwitch!)
{
    if (sender.on == true){
        print("on")
    }
    else{
        print("off")
    }
}

我不断收到错误,所以我按照Xcode的建议进行操作,结果以SIGBART错误结束.

I kept getting errors so I did what Xcode suggested which ended up with the SIGBART error.

推荐答案

您在addTarget操作行上错误地调用了选择器.他们终于在Swift 2中的某个时刻对其进行了更改,以摆脱使用字符串进行选择器方法调用的麻烦,这现在使它们更不容易出错.

You are calling the selector wrong on the addTarget action line. They finally changed it at one point in Swift 2 to get rid of using strings for selector method calls, which now makes them a lot less error prone.

将其更改为此(Swift 3语法)

Change it to this (Swift 3 syntax)

switchDemo.addTarget(self, action: #selector(switchValueDidChange(_:)), for: .valueChanged)

基本上,您在action参数中调用#selector,并包含要调用的方法(在本例中为switchValueDidChange).请注意最后的(_ :)语法,这表示您要调用的方法带有一个参数,在您的情况下为UISwitch.

You basically call #selector in the action parameter and include the method you want to call, in your case switchValueDidChange. Note the (_:) syntax at the end, thats indicating that the method you want to call takes a parameter, in your case a UISwitch.

 func switchValueDidChange(_ sender: UISwitch) {
     ...
 }

如果您要调用不带任何参数的常规方法,例如

If you want to call a regular method that takes no parameters e.g

 func switchValueDidChange() {
 }

比你只会说

switchDemo.addTarget(self, action: #selector(switchValueDidChange), for: .valueChanged)

没有(_ :)语法.

希望这会有所帮助

这篇关于UISwitch:Swift 3:以编程方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆