【问题标题】:Add NSClickGestureRecognizer to NSButton programmatically swift以编程方式将 NSClickGestureRecognizer 添加到 NSButton
【发布时间】:2015-03-30 14:36:45
【问题描述】:

我有多个使用此代码生成的 NSButton:

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
}

并且我需要将NSClickGestureRecognizer 添加到它们中的每一个以识别辅助鼠标按钮点击。有没有办法以编程方式做到这一点?

【问题讨论】:

    标签: xcode cocoa swift gesture nsbutton


    【解决方案1】:

    这应该可行:

    let g = NSClickGestureRecognizer()
    g.target = self
    g.buttonMask = 0x2 // right button
    g.numberOfClicksRequired = 1
    g.action = Selector("buttonGestured:")
    but.addGestureRecognizer(g)
    

    以后

    func buttonGestured(g:NSGestureRecognizer) {
        debugPrintln(g)
        debugPrintln(g.view)
        if let v = g.view as? NSButton {
            debugPrintln("tag: \(v.tag)")
        }
    }
    

    【讨论】:

    • 谢谢你,这正是我要找的!
    • g.action = Selector("buttonGestured:") 现在必须写成g.action = #selector(ViewController.buttonGestured(_:))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-20
    • 2014-07-20
    • 2012-05-09
    • 2011-03-14
    • 2016-07-24
    • 2012-08-06
    相关资源
    最近更新 更多