问题
I'd like to create an array of buttons with a script. This includes setting the size and position and assigning a mouseUp hander go them.
The mouseUp handler should be
on mouseUp
go to card "aName"
end mouseUp
The list of names is in a text variable tCardNames. Each line has a card name.
回答1:
Here's a slightly different approach. The repeat for each form is more efficient for long lists than repeat with, but in this situation there would likely be no appreciable difference.
on createButtons
repeat for each line tBtnName in tCardNames
createNamedButton tBtnName
end repeat
end createButtons
on createNamedButton pName
create button pName
set the script of btn pName to "on mouseUp" & cr & \
"go cd " & quote & pName & quote & cr & \
"end mouseUp"
put the number of btn pName into tNum
set the top of btn pName to (10 * 30 * (tNum - 1))
end createNamedButton
回答2:
The following script does the job
on createButtons
repeat with i = 1 to the number of lines of tCardNames
put line i of field "cardNames" into tName
createNamedButton i, tName
end repeat
end createButtons
on createNamedButton n, aName
create button
set the label of it to aName
put "on mouseUp" & return into s
put "go to cd " & quote & aName & quote& return after s
put "end mouseUp" after s
set the script of it to s
put (10 + 30 * (n -1)) into tDistanceFromTop
set the top of it to tDistanceFromTop
end createNamedButton
回答3:
That script should work fine, but since all the buttons have basically the same script, you could omit the script part of the handler, and assign them a behavior instead. This is a good example of when to use a behavior. The behavior button script would be something like this:
on mouseUp
go cd (the label of the target)
end mouseUp
Create that button, name it "goCardBehavior", hide it, and in your original handler add this line instead of the part that writes the script:
set the behavior of it to the long ID of button "goCardBehavior"
One advantage of using behaviors is that when you need to change the script later, you only have to do it in one place.
来源:https://stackoverflow.com/questions/17122755/how-do-i-create-an-array-of-buttons-with-a-script