【问题标题】:Is it possible to access a TButton using tag?是否可以使用标签访问 TButton?
【发布时间】:2010-12-22 14:32:43
【问题描述】:

我希望使用标签访问 TButton。 有可能吗?

例如,我希望将 TButton(button1 有标签 3)的标题设置为 'aaa', 我知道我可以使用

button1.caption:='aaa';

但我希望使用标记'3'来访问tbutton并设置字符串值'aaa'。

欢迎评论

谢谢

交互开发

【问题讨论】:

  • 你会更加明确地知道你想要做什么。
  • @user262325 - 您是否拥有唯一的标签,或者您想为多个组件设置标题(为多个按钮设置相同的标签)?

标签: delphi


【解决方案1】:
procedure TForm1.ChnCaptionByTag(SearchTag: integer; NewCpt: string);
var
  i: Integer;
begin
  for i := 0 to ComponentCount - 1 do
    if Components[i] is TButton then
    begin
      if TButton(Components[i]).Tag = SearchTag then
         TButton(Components[i]).Caption := NewCpt;
    end;
end;

【讨论】:

  • Maaan 我总是迟到。我给出了同样的答案。按钮之间的标签也必须是唯一的,否则,您将拥有带有指定标签的最后一个按钮。
  • 对不起,收回,Break 怎么样;从循环
  • @daemon: 如果 user262325 有多个相同标签的按钮?
【解决方案2】:

没有直接的办法

 ButtonByTag(3).Caption := 'aaa';

您可以搜索表单的组件以查找标签为 3 的内容:

 var C: TComponent;

 for C in Self.Components do
    if C is TCustomButton then
      if C.Tag = 3 then
        (C as TCustomButton).Caption := 'aaa'

但请注意,您可以有很多具有相同标签的组件,但不能保证唯一。

【讨论】:

  • 很好——我从来不知道“for C in self.components”;我总是做“for i:=0 to ControlCount (or componentcount)”
  • 休息怎么样?从循环?
  • @M Schenkel - 从 2005 年开始
  • @daemon_x:我假设 OP 想要所有带有标签 3 的按钮。如果他只想要第一个按钮,那么是的,break 是要走的路。
  • @Larry Lustig - 谁知道?他可能对答案很满意,所以这可能是下一个不被接受的解决方案:(
【解决方案3】:

我认为这应该可行:

procedure TForm1.SetCaption(iTag: Integer; mCaption: String);
var
  i: Integer;
begin
  for i:= 0 to controlcount-1 do
    if controls[i] is TButton then
      if TButton(controls[i]).Tag = iTag then
        TButton(controls[i]).Caption := mCaption;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  SetCaption(3,'aaa');
end;

【讨论】:

  • 休息怎么样?从循环?
  • 原来的问题没有说明多个按钮是否可以共享同一个标签...提前break可能是错误的。
  • +1 为你的论点。由于广告减少,我还想要一些积分:P
  • 要坚持,你可以给参数“const”类型:)
【解决方案4】:

好吧,现在 Tag 属性的大小与 Pointer 相同,所以你可以,但你需要多描述一下你想做的事情。 p>

我不肯定这种情况会继续出现在 64 位 Delphi 中,但我认为情况也是如此。

编辑:是的,TComponent.Tag 在未来的版本中应该是NativeInt。参考文献:Barry KellyAlexandru Ciobanu

【讨论】:

  • 今年在巴西的一次会议上,David I. 说明年会有 64 位和 MAC 编译器 -- 如果代码编译为 64 位,Tag 属性将是一个 64 大整数平台。
  • mac编译器?是苹果mac的吗?
  • @user262325 - 是的,有计划为 Delphi 制作 Mac 编译器。见Roadmap
【解决方案5】:
procedure TForm1.ChangeCaptionByTag(const SearchTag: integer; const NewCaption: string);
var i: Integer;
begin
  for i in Components do
    if Components[i] is TButton then
      if (Components[i] as TButton).Tag = SearchTag then
        begin
          (Components[i] as TButton).Caption := NewCaption;
          Break;
        end;
end;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-11
    • 1970-01-01
    • 2014-01-03
    相关资源
    最近更新 更多