applescript:将 "whose" 和 "exists" 放入同一行

applescript: work "whose" and "exists" into the same line

我的问题最好用一行代码来说明:

tell application "System Events" to tell application process "Dock" ¬
to tell list 1 to first UI element whose value of attribute "AXTitle" ¬
is "Trash"

这以错误结束,因为并非 Dock 中的每个 UI element 都有 attribute "AXTitle"dock separator item只有AXRoleAXRoleDescription

我想知道 是否有办法让代码 return 正确 UI element 尽管如此。

这是我尝试过但失败了的方法:

1) try block: 这只是跳过这行代码并继续下一行

2) 忽略应用程序响应块:同上。

3) exists(attribute "attributeName"):我能够测试每个人 UI element 例如exists (attribute "AXTitle") of UI element 1,但我无法将 exists 转化为 whose 语句:它应该看起来像这样:

UI elements whose (exists (attribute "AXTitle") is true)

那是行不通的。现在我必须 运行 一个 repeat with 循环,里面有一个 if 语句,还有一个 exit repeat 这样我就可以循环遍历所有内容。这很麻烦。

必须有更好的方法。

澄清:一些人向我展示了到达 Trash 的更优雅的方法。我以 Trash 为例,但意思是问题更广泛,即 当列表中的项目缺少此属性时,如何根据属性找到列表的第一项.另一个例子是:

delay 5
tell application "System Events" to tell application process "Dock" ¬
to tell list 1 to first UI element whose value of attribute ¬
"AXSelected" is true

然后将光标移动到 Dock 中的任意项目。此示例失败,因为再次 Dock Separator 没有公共字段 "AXSelected"。

这对我有用,而且更好,因为 "Trash" 的标题已本地化,这里是 "Papirkurv"。 :)

tell application "System Events" to tell process "Dock"
    tell list 1
        get first UI element whose value of attribute "AXSubrole" is "AXTrashDockItem"
    end tell
end tell

如果您安装了 Xcode,那么您应该有一个名为 UIElementInspector 的应用程序,它可以让您读取 UI 元素的不同值。

只需像这样添加另一个条件:whose subrole is not "AXSeparatorDockItem"

tell application "System Events"
    tell application process "Dock" to tell list 1 to (first UI element whose subrole is not "AXSeparatorDockItem" and its selected is true)
end tell 

--

Update : 你可以用title 属性代替value of attribute "AXTitle",这样不会报错。

tell application "System Events"
    tell application process "Dock" to tell list 1 to UI elements whose title is "Trash"
end tell