如何在LaTeX Beamer中不使用table环境创建带编号的表格标题
解决方案
要给自定义表格标题添加自动编号,我们可以利用LaTeX的计数器机制,结合你的自定义命令实现,同时保留NiceTabular和对齐需求。以下是修改后的完整代码:
\documentclass[aspectratio=169,xcolor=table,12pt]{beamer} % compile in pdfLaTeX \usepackage{caption} \usepackage{booktabs} \usepackage{nicematrix} \NiceMatrixOptions{cell-space-limits = 2pt} \definecolor{tableYellowHeaderBg}{RGB}{250,191,18} \definecolor{tableYellowCellBg}{RGB}{255,242,204} \definecolor{tableYellowLines}{RGB}{250,191,18} \definecolor{tableYellowCellFg}{RGB}{127,127,127} % 带自动编号的黄色表格标题命令 \newcommand{\myCaptionYellow}[1]{% \refstepcounter{table} % 递增表格计数器,支持交叉引用 {% \usebeamercolor[fg]{tableYellowCellFg}% \usebeamerfont*{caption name}% Table \thetable% 输出带编号的标签 \usebeamertemplate{caption label separator}% }% \usebeamerfont*{caption name} #1\par } % 带自动编号的灰色表格标题命令(同理修改) \newcommand{\myCaptionGrey}[1]{% \refstepcounter{table} {% \usebeamercolor[fg]{tableGreyCellFg}% \usebeamerfont*{caption name}% Table \thetable% \usebeamertemplate{caption label separator}% }% \usebeamerfont*{caption name} #1\par } \begin{document} \begin{frame}[t]{Tables} \raggedleft \myCaptionYellow{This is a table caption.}\label{tab:first} % 添加标签用于交叉引用 \begin{NiceTabular}[c]{wc{1.0cm}wc{1.0cm}wc{1.0cm}wc{1.0cm}}[rules/color=tableYellowLines] \CodeBefore \rowcolor{tableYellowHeaderBg}{1} \rowcolors{2}{}{tableYellowCellBg} \Body \toprule[1.5pt] \RowStyle{\color{white}}H1 & H2 & H3 & H4 \\ \arrayrulecolor{white}\toprule[1.5pt] \RowStyle[nb-rows=*]{\color{tableYellowCellFg}}Cell 1 & Cell 2 & Cell 3 & Cell 5 \\ \midrule Cell 5 & Cell 6 & Cell 7 & Cell 8 \\ \midrule Cell 9 & Cell 10 & Cell 11 & Cell 12 \\ \bottomrule \end{NiceTabular} % 示例:交叉引用表格 \vspace{1em} 请参考表\ref{tab:first} \end{frame} \begin{frame}[t]{第二个表格} \raggedleft \myCaptionYellow{这是第二个表格的标题。}\label{tab:second} \begin{NiceTabular}[c]{wc{1.5cm}wc{1.5cm}}[rules/color=tableYellowLines] \CodeBefore \rowcolor{tableYellowHeaderBg}{1} \rowcolors{2}{}{tableYellowCellBg} \Body \toprule[1.5pt] \RowStyle{\color{white}}列1 & 列2 \\ \arrayrulecolor{white}\toprule[1.5pt] \RowStyle{\color{tableYellowCellFg}}内容A & 内容B \\ \bottomrule \end{NiceTabular} \end{frame} \end{document}
关键修改说明:
- 计数器自动递增:在自定义命令中加入
\refstepcounter{table},每次调用命令时自动递增内置的table计数器,实现连续编号。 - 简化命令参数:将原命令的两个参数合并为一个,标签部分自动生成
Table \thetable(\thetable输出当前计数器值)。 - 修复颜色名错误:将原代码中未定义的
UnthaTableYellowCellFg改为你已定义的tableYellowCellFg。 - 支持交叉引用:通过
\label和\ref实现表格的交叉引用,符合标准LaTeX使用习惯。 - 保留对齐设置:保留
\raggedleft实现标题右对齐的需求,不依赖table环境。
内容的提问来源于stack exchange,提问作者Konrad
相关产品推荐
相关产品推荐

