利用按钮来执行命令

在Cocoa框架中,所有的按钮都是基于NSButton,系统提供了多钟按钮,下面显示部分:

将多个用户界面子项与一个IBAction连接起来:

首先,利用一个子项创建一个IBAction方法,然后选中另一个子项,按住Ctrl键,将鼠标拖到刚刚创建的IBAction方法上,直到整个方法高亮再松开即可:

代码如下:

AppDelegate.swift代码

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    @IBOutlet weak var window: NSWindow!

    @IBOutlet weak var displayLabel: NSTextField!

    func applicationDidFinishLaunching(aNotification: NSNotification) {
    }

    func applicationWillTerminate(aNotification: NSNotification) {
    }

    @IBAction func displayButton(sender: AnyObject) {

        if sender is NSButton {
            let whichObject=sender as! NSButton
            switch whichObject.tag {
            case 0:
                displayLabel.stringValue="Push Button"
            case 1:
                displayLabel.stringValue="Recessed Button"
            case 2:
                displayLabel.stringValue="Inline Button"
            default:
                displayLabel.stringValue="Unknow"
            }
        }

    }

}

学习Pop-Up按钮

1.修改Pop-Up菜单项
在用户界面上双击pop-up按钮,便会出现菜单项目,添加菜单项的方法:在对象库中找到Menu Item,将其拖到Pop-Up菜单项列表中即可:

效果图:

当然,可以通过代码来添加Pop-Up菜单项,使用myPopUp.addItemWithTitle("东方卫视")或者myPopUp.addItemsWithTitles(["浙江卫视","辽宁卫视"])

代码如下:

AppDelegate.swift文件:

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    @IBOutlet weak var window: NSWindow!

    @IBOutlet weak var myPopUp: NSPopUpButton!
    @IBOutlet weak var infoInput: NSTextField!
    func applicationDidFinishLaunching(aNotification: NSNotification) {
    }

    func applicationWillTerminate(aNotification: NSNotification) {
    }


    @IBAction func showChoice(sender: NSPopUpButton) {
            print("\(sender.titleOfSelectedItem!)")

    }

    @IBAction func addMenu(sender: AnyObject) {

        myPopUp.addItemWithTitle(infoInput.stringValue)

    }


    @IBAction func deleteMenu(sender: AnyObject) {

        myPopUp.removeItemAtIndex(0)

    }

}

效果图:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值