swift:收音机菜单如何?它们是互斥的?

时间:2014-07-30 16:52:38

标签: macos swift swift-playground

enter image description here 我想实现收音机菜单,这是我们这一代的菜单

subMenu.addItemWithTitle("Item001", action: Selector("testAction:"), keyEquivalent: "\(code)")
subMenu.addItemWithTitle("Item002", action: Selector("testAction:"), keyEquivalent: "\(code)")
subMenu.addItemWithTitle("Item003", action: Selector("testAction:"), keyEquivalent: "\(code)")
subMenu.addItemWithTitle("Item004", action: Selector("testAction:"), keyEquivalent: "\(code)")
subMenu.addItemWithTitle("Item005", action: Selector("testAction:"), keyEquivalent: "\(code)")
subMenu.addItemWithTitle("Item006", action: Selector("testAction:"), keyEquivalent: "\(code)")

enter image description here 广播菜单如何?

func testAction(sender: NSMenuItem){
    sender.state = Int(!Bool(sender.state))
    if(sender.action == Selector("testAction:")){
        var itemMore:NSMenuItem!
        for itemMore:AnyObject in sender.menu.itemArray {
            if (itemMore.action() == sender.action){
                itemMore.state = (itemMore == sender) ? NSOnState : NSOffState;
            }
        }
    }
}

3 个答案:

答案 0 :(得分:4)

首先,解决方案:

func testAction(sender: NSMenuItem){
    sender.state = Int(!Bool(sender.state))
    if(sender.action == Selector("testAction:")){
        for itemMore in sender.menu.itemArray as [NSMenuItem!]{
            if (itemMore.action == sender.action){
                itemMore.state = (itemMore == sender) ? NSOnState : NSOffState;
            }
        }
    }
}

现在解释: 要设置menuItem的state属性,编译器必须知道它是NSMenuItem类型。这是通过for-in循环中的向下转换来完成的:as [NSMenuItem!],正如我所看到的那样,您尝试使用上面的行:var itemMore:NSMenuItem!。 (你现在可以删除它。)你正确地选择了一个隐式解包的可选项,因为menu.itemArray保证不包含nil值。

如果不这样做,编译器会将menuItem视为AnyObject,它恰好具有NSURLSesionTaskState类型的属性,也称为“state”。尝试将其设置为Int(实质上是NSOnState / NSOffState)会引发编译器错误。

答案 1 :(得分:1)

这个怎么样

func testAction(sender: NSMenuItem){
    sender.state = Int(!Bool(sender.state))
    if(sender.action == Selector("testAction:")) {
        var itemMore:NSMenuItem!
        for itemMore:AnyObject in sender.menu.itemArray {
            if let menuItem = itemMore as? NSMenuItem {  // -- need to downcast first
                if (menuItem.action == sender.action){
                    menuItem.state = (menuItem == sender) ? NSOnState : NSOffState;
                }
            }
        }
    }
}

答案 2 :(得分:0)

我将在Objective-C中写作。翻译成Swift取决于你。

for (NSMenuItem* item in [[sender menu] itemArray])
{
    if (item.action == sender.action)
        item.state = (item == sender) ? NSOnState : NSOffState;
}