Silver Challenge


#1

HI
I took a quite different approach:
I added a XIB file and set the BNRHypnosisView as it’s view.
Then you can the remove the “initWithFrame” completely from this view. Hoewver you must set the default circleColor int the controller:
Actually, if you do not remove this code it will not work, for you are in effect destroying the “old view” and making a new one.
You must also remove the load view function.

if(self)
    {
        BNRHypnosisView  *testView =  (BNRHypnosisView *)  self.view;
        testView.circleColor = [UIColor lightGrayColor];
        self.tabBarItem.title = @"Hypnotize";
        //Create a UIImage from a file
        //This will use the Hypno@2x.png on retina display devices
        UIImage *i = [UIImage imageNamed:@"Hypno.png"];
        //Put that image on the tab bar item
        self.tabBarItem.image = i;
    }

The you just drag a UISegmented control to the BNRHypnosisView, set the number of segments to 3 and give them their names.
And catch the action in the controller file:

[code]- (IBAction)setColor:(UISegmentedControl *)sender
{
NSLog(@“The object is %ld”, sender.selectedSegmentIndex);
BNRHypnosisView *drawView = (BNRHypnosisView *) self.view;
if (sender.selectedSegmentIndex == 0) {
drawView.circleColor = [UIColor redColor];
} else if( sender.selectedSegmentIndex == 1) {
drawView.circleColor = [UIColor greenColor];
}else if (sender.selectedSegmentIndex == 2)
{
drawView.circleColor = [UIColor blueColor];
}
[drawView setNeedsDisplay];

}
[/code]
You can of course omit the NSLog… I just made it to se if it worked. The trick is the “setNeedsDisplay”, which redraws the view with the new colour.

comments are welcome :unamused:


#2

So, we can mix the programmatically created view with xib file. It sounds interesting.

Just one thing; setNeedsDisplay in setColor seems not necessary since setCircleColor already has it.


#3

No, you do need the “setNeedDisplay”, as it implicitly calls the drawRect method. Otherwise nothing will happen, the view will not be updated.
PS: setColor is a bad name for the method as it uses the same syntax as Objective C it self uses for properties (setter methods). I have changed it to “updateColor”.
It did not mean anything here, but in other cases it might lead to very strange bugs.


#4

As sunny4s pointed out, you don’t need setNeedsDisplay: here - This message should instead be sent in UIDrawView’s setCircleColor:.


#5

Ahh, sorry you are quite right. Of course. No need to call it twice. Thanks both of you!