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