How Do I Load or Update a View From NSObject Class After Getting the Data?

391 views Asked by At

I'm having a bit of trouble updating my UIImageView to contain subviews of buttons after I'm getting the CGPoint data from another class. In my main VC, I've got an ImageView set as a subview to a UIScrollView that is a subview of the main ViewControllers view.

In viewDidLoad, I'm calling a method from an NSObject class to get the data for all the button locations from my database:

- (void)parseCoordinateData:(NSArray*)data {
    NSLog(@"Processing Data");

    mapVC = [[ViewController alloc]init];

    for(NSArray *table in data) {
        NSLog(@"Table: %@", table);

        float xValue = [[NSString stringWithFormat:@"%@", [table[0]objectForKey:@"LocationX"]] floatValue];
        float yValue = [[NSString stringWithFormat:@"%@", [table[0]objectForKey:@"LocationY"]] floatValue];

        NSLog(@"Coordinates: (%f,%f)", xValue, yValue);

        CGPoint buttonCoordinate = CGPointMake(xValue, yValue);

        [mapVC placeButtonsFromDatabaseWithCoordinates:buttonCoordinate];

   }
}

And in the method from the main VC where I'm placing the buttons:

- (void)placeButtonsFromDatabaseWithCoordinates:(CGPoint)point {

    NSLog(@"Placing Button at point: %@", NSStringFromCGPoint(point));

    UIButton *button = [[UIButton alloc] init];

    [self.imageView addSubview:button];

    button.frame = (CGRect){.origin = point, .size = CGSizeMake(20.0, 20.0)};
    button.backgroundColor = [UIColor greenColor];
    button.layer.cornerRadius = 10;
    button.clipsToBounds = YES;
    button.userInteractionEnabled = YES;
    [self animateButton:button];

    [self.imageView bringSubviewToFront:button];  
    }

But the buttons are not appearing on the image view. Any idea how to get this to work?

EDIT

I've created a very small project to try and replicate this problem. I've created a view controller that calls to an NSObject class that will call back to the View Controller to draw a subview. I am getting an EXC BAD ACCESS error when attempting this.

However, if handling the call explicitly in the main thread, the app will not crash but the view will not draw.

I think this is what's happening when trying to add the button to the image as a subview.

1

There are 1 answers

2
Misha On

Change

UIButton *button = [[UIButton alloc] init]; 

to

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];