我想问一下如何在多部分矩形节点中添加换行符。
我编写的代码应该可以工作,但实际上却不行。您能告诉我我做错了什么吗,或者我该如何调整才能让它工作。
\tikzstyle{umlclass}=[
draw=black,
fill=yellow!16,
rectangle split,
rectangle split parts = 3,
rectangle split part align={center,left,left},
execute at begin node = \ttfamily,
]
\node[umlclass]{
<<interface>>\\
class
\nodepart{second}
+attribute
};
答案1
您可以简单地使用\parbox
。如果需要,您仍然可以使用\centering
进行对齐。此外,建议使用\tikzset
而不是\tikzstyle
。
\documentclass[10pt]{book}
\usepackage{tikz}
\usetikzlibrary{shapes.multipart}
\tikzset{umlclass/.style={
draw=black,
fill=yellow!16,
rectangle split,
rectangle split parts = 3,
rectangle split part align={center,left,left},
execute at begin node = \ttfamily,
}}
\begin{document}
\begin{tikzpicture}
\node[umlclass]{
\parbox{2.4cm}{\centering
<<interface>>\\
class}
\nodepart{second}
+attribute
};
\end{tikzpicture}
\end{document}
egreg 的非常好的评论,使用表格不需要知道宽度:
\node[umlclass]{
\begin{tabular}{@{}c@{}}
<<interface>>\\
class
\end{tabular}
\nodepart{second}
+attribute
};
答案2
您必须提供align=center
常规node
选项,因为第一个节点部分不会像其他部分一样处理。该 rectangle split part align
选项确实适用于它,但只影响内部使用该选项的框(这也是没有达到预期效果的align
原因)。\\
这意味着需要指定align=center
并rectangle split part align={center,…}
\documentclass[border=5mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{shapes.multipart,positioning}
\tikzset{
umlclass/.style={
draw=black,fill=yellow!16,rectangle split,rectangle split parts = 3,font = \ttfamily},
umlclass -c/.style={
umlclass,align=center,rectangle split part align={left}}, % = left, left, left
umlclass -r/.style={
umlclass,align=right, rectangle split part align={left}}, % = left, left, left
umlclass +/.style={
umlclass,align=center, rectangle split part align={center,left}}} % = center, left, left
\newcommand*{\umlclasscontent}{<<interface>>\\class\nodepart{second}very long attribute\nodepart{third}method()}
\begin{document}
\begin{tikzpicture}
\node[umlclass -c] {\umlclasscontent};
\node[umlclass -r] at (0,-3) {\umlclasscontent};
\node[umlclass +] at (0,-6) {\umlclasscontent};
\end{tikzpicture}
\end{document}