如何按名称单击系统偏好设置 UI 元素的复选框

How to click the checkbox of a System Preferences UI element by name

我有一段 Applescript 目前可以正常使用,并在系统偏好设置 > 安全和隐私 > 联系人中单击了一个复选框。但是,现在它只起作用,因为我明确说明了我定位的应用程序行(在本例中为第 2 行)。这目前工作正常,但如果将来我在该窗格中以不同的应用顺序结束,它将中断。有没有办法遍历给定 window 的所有项目并说“如果 UI 元素是 Alfred 4.app,则单击复选框”?我想强化代码,以便无论应用程序在此窗格中列出的顺序如何,它都能正常工作。

set appName to "Alfred 4.app"
tell application "System Preferences"
    activate
    set the current pane to pane id "com.apple.preference.security.Privacy_Contacts"
    delay 1
end tell
tell application "System Events"
    click checkbox 1 of UI element appName of row 2 of table 1 of scroll area 1 of group 1 of tab group 1 of window "Security & Privacy" of application process "System Preferences"
end tell

在 Catalina 上测试了以下脚本:

set appName to "Alfred 4.app"

tell application "System Preferences"
    activate
    reveal anchor "Privacy_Contacts" of pane id "com.apple.preference.security"
end tell
delay 1

tell application "System Events" to tell process "System Preferences"
    repeat with aRow in (rows of table 1 of scroll area 1 of group 1 of tab group 1 of window "Security & Privacy")
        if name of UI element 1 of aRow is appName then
            click checkbox 1 of UI element 1 of aRow
            exit repeat
        end if
    end repeat
end tell