Short Silver Solution + Question


#1

I only* made changes in the following file:

BNRHypnosisViewController.m (showing the applicable portions)

[code]
@interface BNRHypnosisViewController ()

@property (nonatomic, strong) BNRHypnosisView *backgroundView;

@end

@implementation BNRHypnosisViewController

.
.
.

  • (void)loadView
    {
    // Create a view
    CGRect frame = [UIScreen mainScreen].bounds;
    self.backgroundView = [[BNRHypnosisView alloc] initWithFrame:frame];

    // Set it as the view of this view controller
    self.view = self.backgroundView;

    UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:@[@“Red”, @“Green”, @“Blue”]];
    [segmentedControl addTarget:self
    action:@selector(SegmentControlAction:)
    forControlEvents:UIControlEventValueChanged];
    [self.backgroundView addSubview:segmentedControl];
    }

  • (void)SegmentControlAction:(UISegmentedControl *)segment
    {
    if (segment.selectedSegmentIndex == 0) {
    [self.backgroundView setCircleColor:[UIColor redColor]];
    } else if (segment.selectedSegmentIndex == 1) {
    [self.backgroundView setCircleColor:[UIColor greenColor]];
    } else if (segment.selectedSegmentIndex == 2) {
    [self.backgroundView setCircleColor:[UIColor blueColor]];
    }
    }[/code]

I knew immediately that, if I was going to add the UISegmentedControl programmatically, it would have to be done in the loadView method. But my main problem was in understanding how to make a tap on one of the segment’s buttons perform the action of changing the color. So I dug around online and found the addTarget:action:forControlEvents method. The UISegmentedControl object adds itself as a target, with the handwritten SegmentControlAction: method as its action, which takes place when the value for the UISegmentedControl object changes. The SegmentControlAction: method takes a UISegmentControl object as a parameter. I use the selectedSegmentIndex of the UISegmentControl object to determine whether to change the background of the BNRHypnosis view red, green, or blue.

By default, the looks and positioning of the UISegmentedControl are kind of janky, but the functionality appears to be as intended by the challenge.

  • Actually, this is a bit of a white lie, since I also modified BNRHypnosisView.h to declare the setCircleColor: method. When combined with declaring a BNRHypnosisView property in a class extension at the top of BNRHypnosisViewController.m, this allowed me to access the backgroundView object, along with its setCircleColor: method, from within SegmentControlAction:.

Can somebody enlighten me as to whether it’s actually ideal for this SegmentControlAction: functionality to be occurring in the BNRHypnosisViewController class? That’s the one thing I’m finding most difficult about MVC, really locking down the fundamental division of labor in my head. Should I be delegating this responsibility to another class?