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

izn*_*oud 13 selector nsbutton ios swift

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

pbo*_*dsk 18

问题在于你添加你的方式 selector

myButton.action = Selector(printSomething())
Run Code Online (Sandbox Code Playgroud)

添加选择器的语法有点古怪,你给它一个带有函数名称的字符串,所以在你的情况下你应该写:

myButton.action = Selector("printSomething")
Run Code Online (Sandbox Code Playgroud)

哪个应该Hello在你的控制台中奖励你.

可能是因为语法导致了人们的问题,它在Swift 2.2中被改变了,所以现在你写道:

myButton.action = #selector(ViewController.printSomething)
Run Code Online (Sandbox Code Playgroud)

代替.这意味着编译器可以帮助您尽早发现这些错误,这是我认为的一大进步.你可以阅读更多关于它在雨燕2.2的发布说明这里

所以...这是你的整个例子:

import Cocoa

class ViewController: NSViewController {

    @objc
    func printSomething() {
        print("Hello")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        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(ViewController.printSomething)
    }

    override var representedObject: AnyObject? {
        didSet {
        // Update the view, if already loaded.
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

希望对你有所帮助.