我想用foreach循环放置节点,但是下面的代码报错!
\documentclass[border=3mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{positioning}
\begin{document}
\begin{tikzpicture}
\node (A) {A};
\node [below=1 of A] (B) {B};
\foreach \name/\pos in {C/below=1 of B,D/below=1 of C} {
\node [\pos] (\name) {\name};
}
\end{tikzpicture}
\end{document}
错误信息:
! Package pgfkeys Error: I do not know the key '/tikz/below=1 of B' and I am go
ing to ignore it. Perhaps you misspelled it.
See the pgfkeys package documentation for explanation.
Type H <return> for immediate help.
答案1
当谈到哪里需要自己确保扩展,哪里不需要的问题时,我没有在 TikZ 中看到严格的概念。
尝试:
\documentclass[border=3mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{positioning}
\begin{document}
\begin{tikzpicture}
\node (A) {A};
\node [below=1 of A] (B) {B};
\foreach \name/\pos in {C/below=1 of B,D/below=1 of C} {
\expanded{\unexpanded{\node}[\pos](\name){\name}};
}
\end{tikzpicture}
\end{document}
答案2
虽然它应该按照您建议的方式工作,但我认为最好确保结构并分离变量以获得更灵活的迭代。
结果:
梅威瑟:
\documentclass[border=3mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{positioning}
\begin{document}
\begin{tikzpicture}
\node (A) {A};
\foreach \nodename/\pos/\lastnodename/\nodetext in {
B/below/A/B,
C/below/B/C,
D/left/A/left of A,
E/above/A/above of A,
G/below left/C/below left of C% <- The percentage symbol is necessary to have that object format per line
}
{
\node [\pos=1 of \lastnodename] (\nodename) {\nodetext};
}
\end{tikzpicture}
\end{document}