Programmatically added UIScrollView used in multip

2019-08-26 02:01发布

问题:

So what i am trying to do is to have a screen that every time I press a button it adds a new image view to the UIScrollView i created, but i ran into a problem... because the uiscrollview was created in the viewDidLoad it isn't declared for use in the later methods... so my question is basically... how do i get around this?

int pixels = 20;
int playerCount = 2;
-(void) viewDidLoad{

UIScrollView *mainScroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, 320, 400)];
mainScroll.contentSize = CGSizeMake(320, 700);
mainScroll.showsHorizontalScrollIndicator = YES;
[self.view addSubview:mainScroll];
[mainScroll setScrollEnabled:YES];


UIButton *addPlayersButton = [UIButton buttonWithType: UIButtonTypeRoundedRect];

[addPlayersButton addTarget:self
                     action:@selector(addPlayer)
           forControlEvents:UIControlEventTouchUpInside];
[mainScroll addSubview: addPlayersButton];
    addPlayersButton.frame = CGRectMake(20, pixels, 50, 50);



-(void)addPlayer{
pixels += 90;
playerCount++;

if (playerCount <= 7) {
    UIImageView *player3 = [[UIImageView alloc]initWithFrame: CGRectMake(15, pixels, 290, 80)];
    player3.image = [UIImage imageNamed:@"player1Bar.png"];
    [mainScroll addSubview:player3];
}

回答1:

I figured out that what i needed to do was to make the UIScrollView in the .h file and synthesize it in order to be able to use it in multiple methods