如果在swift中按下NSButton,则创建简单的动作

我正在快速学习.我想知道如果按下一个按钮,如何以编程方式调用一个函数….我试过这个,但该函数在程序启动时直接执行,而不是当我按下按钮时……你能不能帮助我解决这个问题..谢谢
在这个测试应用程序的完整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.
        }
    }
}

希望对你有所帮助.

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...