【问题标题】:How to reference a subview without outlet如何引用没有插座的子视图
【发布时间】:2010-02-14 22:19:43
【问题描述】:

刚开始 iPhone 开发,我似乎错过了一些基本的东西。

在基于视图的应用程序中,我在 ViewController 实现文件中以编程方式添加 UIView 子类,并且可以设置一个值:

- (void)viewDidLoad {

    [super viewDidLoad];

 CGRect myRect = CGRectMake(20, 50, 250, 320);

 GraphView *graphView = [[GraphView alloc] initWithFrame:myRect];

 [self.view addSubview:graphView];

    graphView.myString = @"Working here";

}

当我尝试使用同一文件中的操作更改相同的值时,构建失败,因为未声明 graphView:

- (void)puschButton1 {


 graphView.myString = @"Not working here";

}

因为我使用 UIView 子类,所以我的 GraphView 实例没有出口。

如何获得对我的子视图的引用?还是应该以其他方式完成?

提前致谢

弗兰克

【问题讨论】:

    标签: iphone uiview uiviewcontroller subview


    【解决方案1】:

    最简单的解决方案是将graphView 设为视图控制器的实例变量,而不是在viewDidLoad 中声明它。

    在您的 .h 文件中添加这样的内容:

    @class GraphView;
    
    @interface MyViewController : UIViewController {
        GraphView *graphView;
    }
    
    // ... method declarations ...
    
    @end
    

    如果你不想这样做,另一种方法是设置graphViewtag属性,然后在需要时调用superview的viewWithTag:方法来检索视图。

    我不确定您所说的“因为我使用 UIView 子类,所以我的 GraphView 实例没有出口”是什么意思。你通常在你的控制器类上声明出口,不管你是否使用UIView的子类。

    顺便说一句,我会注意到您可能应该在某个时候将releaseGraphView 联系起来,否则您会出现内存泄漏。

    【讨论】:

    • 感谢您的快速答复!编译器抱怨:警告:'graphView' 的本地声明使用 addSubview 语句隐藏实例变量。
    • 那是因为你还有这行:"GraphView *graphView = [[GraphView alloc] initWithFrame:myRect];"将其更改为:self.graphView = [[GraphView alloc] initWithFrame:myRect];
    • 大卫,你成就了我的一天! :-) 那是我所缺少的基本东西!非常感谢 Kristopher、David 和 Sam。
    【解决方案2】:

    您可以将graphView 存储为类变量。

    编辑:请注意addSubview 将增加对象的保留计数,在您的班级中的某处您需要平衡allocreleaseaddSubviewremoveFromSuperview 或@ 987654327@.

    【讨论】:

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