如果在swift中按下NSButton,则创建简单的动作
发布时间:2020-12-14 05:25:29 所属栏目:百科 来源:网络整理
导读:我正在快速学习.我想知道如果按下一个按钮,如何以编程方式调用一个函数….我试过这个,但该函数在程序启动时直接执行,而不是当我按下按钮时……你能不能帮助我解决这个问题..谢谢 在这个测试应用程序的完整ViewController. swift下面 //// ViewController.swi
我正在快速学习.我想知道如果按下一个按钮,如何以编程方式调用一个函数….我试过这个,但该函数在程序启动时直接执行,而不是当我按下按钮时……你能不能帮助我解决这个问题..谢谢
在这个测试应用程序的完整ViewController. swift下面 // // ViewController.swift // hjkhjkjh // // Created by iznogoud on 14/05/16. // Copyright ? 2016 iznogoud. All rights reserved. // import Cocoa class ViewController: NSViewController { func printSomething() { print("Hello") } override func viewDidLoad() { super.viewDidLoad() let myButtonRect = CGRect(x: 10,y: 10,width: 100,height: 10) let myButton = NSButton(frame: myButtonRect) view.addSubview(myButton) myButton.target = self myButton.action = Selector(printSomething()) // Do any additional setup after loading the view. } override var representedObject: AnyObject? { didSet { // Update the view,if already loaded. } } }
问题在于添加选择器的方式
myButton.action = Selector(printSomething()) 添加选择器的语法有点古怪,你给它一个带有函数名称的字符串,所以在你的情况下你应该写: myButton.action = Selector("printSomething") 哪个应该在你的控制台中用Hello来奖励你. 可能因为语法导致了人们的问题,它在Swift 2.2中被更改了,所以现在你写道: myButton.action = #selector(ViewController.printSomething) 代替.这意味着编译器可以帮助您尽早发现这些错误,这是我认为向前迈出的一大步.您可以在Swift 2.2 here的发行说明中阅读更多相关信息 所以…这是你的整个例子: import Cocoa class ViewController: NSViewController { func printSomething() { print("Hello") } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let myButtonRect = CGRect(x: 10,height: 10) let myButton = NSButton(frame: myButtonRect) view.addSubview(myButton) myButton.target = self myButton.action = #selector(ViewController.printSomething) } override var representedObject: AnyObject? { didSet { // Update the view,if already loaded. } } } 希望对你有所帮助. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |