如何在没有outlet的情况下引用子视图
刚开始 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 实例没有出口。
我如何获得对我的子视图的引用?或者应该以另一种方式完成?
预先感谢
弗兰克
Just beginning with iPhone development i seem to miss something fundamental.
In a View based application i'm adding programaticaly a UIView subclass in the ViewController implementation file and can set a value:
- (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";
}
When i try to change the same value with an action in the same file, the Build fails because graphView is undeclared:
- (void)puschButton1 {
graphView.myString = @"Not working here";
}
Because I use a UIView subclass there is no outlet for my GraphView instance.
How can i get a reference to my subview? Or should this be done in another way?
Thanks in advance
Frank
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最简单的解决方案是使
graphView
成为视图控制器的实例变量,而不是在viewDidLoad
中声明它。在您的
.h
文件中添加如下内容:如果您不想这样做,另一种方法是设置
graphView
的tag
属性,然后在需要时调用超级视图的 viewWithTag: 方法来检索视图。我不确定你所说的“因为我使用 UIView 子类,所以我的 GraphView 实例没有出口”是什么意思。您通常在控制器类上声明出口,并且是否使用
UIView
的子类并不重要。顺便说一句,我会注意到您可能应该在某个时候
release
该GraphView
,否则您将出现内存泄漏。The easiest solution is to make
graphView
an instance variable for your view controller, instead of declaring it inviewDidLoad
.Put something like this in your
.h
file:If you don't want to do that, another way is to set
graphView
'stag
property, and then call the superview'sviewWithTag:
method to retrieve the view when you need it.I'm not sure what you mean by "Because I use a UIView subclass there is no outlet for my GraphView instance." You generally declare outlets on your controller class, and it doesn't matter whether you are using a subclass of
UIView
.As an aside, I'll note that you should probably
release
thatGraphView
at some point, or you'll have a memory leak.您可以将 graphView 存储为类变量。
编辑:请注意,
addSubview
会增加对象的保留计数,在类中的某个位置,您需要平衡alloc
与release
并且addSubview
与removeFromSuperview
或release
。You could store
graphView
as a class variable.EDIT: note that
addSubview
will increase the retain count of the object, somewhere in your class you will need to balance thealloc
with arelease
and theaddSubview
with aremoveFromSuperview
or arelease
.