【问题标题】:Not able to access programmatically created UIView from outside of the method it is created in [duplicate]无法从 [重复] 创建的方法之外访问以编程方式创建的 UIView
【发布时间】:2014-08-10 23:56:45
【问题描述】:

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

这是我用来创建 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];

【问题讨论】:

    标签: objective-c xcode uiview


    【解决方案1】:

    访问视图的另一种方式

    你可以给endGameView的tag属性设置一个标签(例如1024),你可以通过发送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] ;
    

    【讨论】:

      【解决方案2】:

      在发布后不久发现了这个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]; 
      

      【讨论】:

        猜你喜欢
        • 2018-06-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多