【问题标题】:How do I get the selected item from NSPopUpButton?如何从 NSPopUpButton 获取所选项目?
【发布时间】:2013-08-06 00:50:53
【问题描述】:
property myPopUp : missing value
on startbuttonpressed_(sender)
    if myPopUp's selectedItem = "Item 1"
        display dialog "This is Item 1"
    else
        display dialog "Failed"
    end if
end startbuttonpressed_

我成功编译了这段代码,但是虽然我选择了“项目 1”,但我收到了“失败”的消息。
我认为我的错误是“myPopUp 的 selectedItem”,但我不知道如何更正它。如何从 NSPopUpButton 中获取所选项目?

【问题讨论】:

    标签: macos applescript osx-mountain-lion nspopupbutton


    【解决方案1】:

    如果您查看NSPopUpButton documentation,您将能够看到您可以调用的所有方法以及它继承的内容。在Getting User Selection 下你有:

    – selectedItem
    – titleOfSelectedItem
    – indexOfSelectedItem
    – objectValue
    

    当然这些都是方法,所以如果你想得到所选值的索引,你可以这样调用:

    set my_index to myPopup's indexOfSelectedItem()
    

    查看文档中的indexOfSelectedItem 条目:

    indexOfSelectedItem
    Returns the index of the item last selected by the user.
    
    - (NSInteger)indexOfSelectedItem
    
    Return Value
    The index of the selected item, or -1 if no item is selected.
    

    我们在上面得到了函数的概述,然后是函数的用法,最后是返回值的描述。这告诉我们indexOfSelectedItem 不带任何参数(如果有,它看起来像- (NSInteger)indexOfItemWithTitle:(NSString *)title)。左边的返回值将是一个 NSInteger,NOT 是一个 Applescript Integer。尽管 Applescript 可能能够以同样的方式处理它,但在某些情况下这会给您带来问题。解决方案是永远不要将 NSString 视为 AS 字符串,也永远不要将 NSInteger 视为 AS 整数。要进行转换,我们必须将其更改为 AS 字符串,然后再更改为 AS 整数:

    set my_index to ((myPopup's indexOfSelectedItem()) as string) as integer
    

    因此,如果您的代码看起来可以使用indexOfSelectedItem titleOfSelectedItem

    【讨论】:

    • 谢谢。但是“将 my_index 设置为 myPopup 的 indexOfSelectedItem()”也有效。我在没有整数转换的情况下编写了我的代码。我解决了这个问题。
    • @user2648576 就像我说的,根据我的经验,这可能会在 75% 的时间内起作用。只需简单地转换每个 NSInteger 和 NSString 就可以省去很多麻烦和调试,然后不必担心 AS 在 Obj-C 上吓坏了
    • 那么,如果我写“set my_index to ((myPopup's indexOfSelectedItem()) as string + 1) as integer”,会成功吗?
    • 一旦你把它转换成一个字符串,你会得到类似“5”的东西,所以你正在尝试“5”+1。在将其转换为整数后添加加一并完成转换。
    【解决方案2】:

    if 条件应该是这样的:

    if (myPopup's titleOfSelectedItem()) = "Item 1" then
    

    【讨论】:

    • 谢谢。我成功获得了用户对 NSPopUpButton 的选择。
    猜你喜欢
    • 1970-01-01
    • 2013-05-31
    • 2014-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    相关资源
    最近更新 更多