ios - 如果 swift 按下 NSButton,则创建简单的 Action

标签 ios swift selector nsbutton

我正在学习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 {

    @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.
        }
    }
}

希望对你有帮助。

关于ios - 如果 swift 按下 NSButton,则创建简单的 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37741441/

相关文章:

objective-c - 我可以假设并处理 Objective-C 中的 SEL 作为指向某物的指针吗?

ios - 指示第 0 行崩溃的崩溃报告?

ios - 使用背景上下文时无法在不同上下文中的对象之间建立关系

ios - swift 中指向方法的指针数组

ios - 如何手动弃用成员

json - 解析开头有定义的Json

ios - 无法识别的选择器 isPitched 被调用

ios/xcode XCTest/XCTest.h 添加图片后找不到错误

ios - 在 Swift 中检测 CAShapeLayer 上的点击?

ios - 使用 CoreBluetooth 以编程方式启用/禁用蓝牙