macos - 如何从 NSPopUpButton 获取所选项目?

标签 macos applescript osx-mountain-lion nspopupbutton

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_

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

最佳答案

如果你看看 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,不是 一个 Applescript 整数。尽管 Applescript 可能会以同样的方式处理它,但在某些情况下,这可能会给您带来问题。解决方案是永远不要将 NSString 视为 AS String 并且永远不要将 NSInteger 视为 AS Integer。要进行转换,我们必须将其更改为 AS 字符串,然后更改为 AS 整数:
set my_index to ((myPopup's indexOfSelectedItem()) as string) as integer

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

关于macos - 如何从 NSPopUpButton 获取所选项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18056048/

相关文章:

objective-c - OSStatus 的 NSError

macos - QKeySequence::退格键

applescript - 循环播放文件夹中的视频文件以获取视频长度

phpunit - OSX 10.8 山狮 PEAR/PHPUnit 不工作

ruby-on-rails - Mac OS X 山狮 "Rails is not currently installed on this system."

ios - AppKit 和 UIKit 有什么区别?

ios - 检查类型为 "NeXT/Apple typedstream"版本 4 (NSArchiver) 的文件

applescript - Apple Music API - 搜索歌曲并创建播放列表 (MacOS)

applescript - Apple 脚本错误 Finder 出现错误 : AppleEvent handler failed

automation - xdotool与山狮和Macbook视网膜