pom*_*nto 2 right-click nsbutton swift
我有许多以编程方式制作的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
}
Run Code Online (Sandbox Code Playgroud)
小智 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
}
Run Code Online (Sandbox Code Playgroud)
在功能中,rightClick您可以通过以下方式访问按钮:
func rightClick(sender : NSGestureRecognizer) {
if let but = sender.view as? NSButton {
// access the button here
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1457 次 |
| 最近记录: |