我有许多以编程方式制作的NSButton,我需要识别,如果用鼠标右键按下其中一个按钮。有没有办法在swift中做到这一点?
创建按钮的代码:
var height = 0
var width = 0
var ar : Array<NSButton> = []
var storage = NSUserDefaults.standardUserDefaults()
height = storage.integerForKey("mwHeight")
width = storage.integerForKey("mwWidth")
var x = 0
var y = 0
var k = 1
for i in 1...height {
for j in 1...width {
var but = NSButton(frame: NSRect(x: x, y: y + 78, width: 30, height: 30))
but.tag = k
but.title = ""
but.action = Selector("buttonPressed:")
but.target = self
but.bezelStyle = NSBezelStyle(rawValue: 6)!
ar.append(but)
self.view.addSubview(but)
x += 30
k++
}
y += 30
x = 0
}
答案 0 :(得分:6)
我找到了解决方案。您可以使用以下代码为每个按钮添加NSClickGestureRecognizer
:
var x = 0
var y = 0
k = 1
for i in 1...height {
for j in 1...width {
var but = NSButton(frame: NSRect(x: x, y: y + 78, width: 30, height: 30))
but.tag = k
but.title = ""
but.action = Selector("buttonPressed:")
but.target = self
but.bezelStyle = NSBezelStyle(rawValue: 6)!
var ges = NSClickGestureRecognizer()
ges.target = self
ges.buttonMask = 0x2 //for right mouse button
ges.numberOfClicksRequired = 1
ges.action = Selector("rightClick:")
but.addGestureRecognizer(ges)
ar.append(but)
self.view.addSubview(but)
x += 30
k++
}
y += 30
x = 0
}
在功能rightClick
中,您可以通过以下方式访问该按钮:
func rightClick(sender : NSGestureRecognizer) {
if let but = sender.view as? NSButton {
// access the button here
}
}
答案 1 :(得分:0)
你的按钮按下&#39;将使用按下的NSButton调用函数。
func buttonPressed(b:NSButton) {
debugPrintln(b.tag)
}
该代码将打印出您按下按钮时指定的按钮标记。