【问题标题】:How to check if a control has been already added to the view?如何检查控件是否已添加到视图中?
【发布时间】:2009-09-13 20:30:35
【问题描述】:

我在视图上添加了一个标签 UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, 320.0f, 300.0f, 75.0f)]; [titleLabel setText:[BusinessLogic 实例].homeMessage];

然后我移动到另一个视图并返回。这导致两个标签控件彼此重叠。我想做的是: 检查是否已经添加了标签控件。如果不添加它并设置文本。如果是,只需设置文本即可。

最好的方法是什么。我想学习正确的方法,因为我已经有了一些令人作呕的方法。

谢谢。 甲乙

【问题讨论】:

    标签: iphone iphone-sdk-3.0


    【解决方案1】:

    你可以查看superview属性:

    if (titleLabel.superview == self) {
    }
    

    (假设“self”是您要添加标签的视图)

    【讨论】:

    • 我想说,他应该先将 UILabel 变量移到函数之外。然后检查是否为零。
    【解决方案2】:
    if (titleLabel.superview != someView) {
        [someView addSubview:titleLabel];
    }
    

    【讨论】:

      【解决方案3】:

      向您的类添加一个属性以存储对您的标签的引用。如果你不把它存储在任何地方,你以后就不能轻易地改变它的文本:

      // header
      @property (nonatomic, retain) IBOutlet UILabel *titleLabel;
      // implementation
      @synthesize titleLabel;
      

      如果titleLabel 是nil,则创建UILabel 实例并分配给它:

      if (self.titleLabel == nil) {
         UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, 320.0f, 300.0f, 75.0f)];
         self.titleLabel = titleLabel;
         [titleLabel release];
         // add to the view here.
      }
      self.titleLabel.text = newText;
      

      【讨论】:

      • 小错字:@synthesis -> @synthesize
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-21
      相关资源
      最近更新 更多