Line break in multipart rectangle node with align specification
You could simply use a \parbox
. You still could use \centering
for the alignment, if desired. Furthermore it's recommended to use \tikzset
instead of \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}
The very good comment of egreg, to use a tabular to not need to know the width:
\node[umlclass]{
\begin{tabular}{@{}c@{}}
<<interface>>\\
class
\end{tabular}
\nodepart{second}
+attribute
};
You have to supply align=center
to the general node
options, as the first node part isn't treated like the others.
The rectangle split part align
option does apply to it, but only affects the box that uses the align
option internally (which is also the reason \\
hasn’t the expected effect).
That means that one need to specify align=center
and 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}