无法从创建它的方法外部访问以编程方式创建的UIView

时间:2014-08-10 23:56:45

标签: objective-c xcode uiview

这可能是一个非常愚蠢的问题,但我已经以编程方式创建了一个UIView,但我似乎无法在代码中的任何地方访问它,除了它所处的实际方法(例如删除)它来自su​​perview或修改视图)。

这是我用来创建UIView的代码:

CGRect frame;
frame.size = CGSizeMake((gameView.bounds.size.width-50), 400);
frame.origin.x = 25;
frame.origin.y = 130;

UIView *endGameView = [[UIView alloc] initWithFrame:frame];
endGameView.backgroundColor = [UIColor colorWithRed:235.0f/255.0f
                                           green:235.0f/255.0f
                                            blue:235.0f/255.0f
                                           alpha:1.0f];

[gameView addSubview:endGameView];

2 个答案:

答案 0 :(得分:0)

访问视图的另一种方式

您可以将标签(例如1024)设置为endGameView的tag属性,并且可以通过发送viewWithTag:1024消息将此视图提取到其超级视图(gameView)。

提示:标签在其超级视图(gameView)的所有子视图中应该是唯一的

CGRect frame;
frame.size = CGSizeMake((gameView.bounds.size.width-50), 400);
frame.origin.x = 25;
frame.origin.y = 130;

UIView *endGameView = [[UIView alloc] initWithFrame:frame];
endGameView.backgroundColor = [UIColor colorWithRed:235.0f/255.0f
                                           green:235.0f/255.0f
                                            blue:235.0f/255.0f
                                           alpha:1.0f];
endGameView.tag = 1024 ;

[gameView addSubview:endGameView];

获取该视图:

// fetch the view
UIView *endGameView = [gameView viewWithTag:1024] ;
[endGameView removeFromSuperView] ;

答案 1 :(得分:-1)

在发布后不久发现此Can't access UIImageView if created programmatically,它完全回答了我的问题。

这就是我为解决这个问题而采取的措施:

Header
UIView *endGameView;

Main // ViewDidLoad
endGameView = [UIView alloc] init];
[self.view addSubView endGame View];

Creation Method

CGRect frame;
frame.size = CGSizeMake((gameView.bounds.size.width-50), 400);
frame.origin.x = 25;
frame.origin.y = 130;

endGameView = [[UIView alloc] initWithFrame:frame];
endGameView.backgroundColor = [UIColor colorWithRed:235.0f/255.0f
                                           green:235.0f/255.0f
                                            blue:235.0f/255.0f
                                           alpha:1.0f];

[gameView addSubview: endGameView];