You declare a delegate in the class header file either above or below the @interface code. You give it a name & list the methods that it can perform. The methods can either be optional or required. Required is the default. The (float)smileForFaceView: is a required method that must be implemented by whoever declares themselves conforming to the delegate. NOTE; that we send a copy of ourself (FaceView) along with the method. This allows the other object to look at the FaceView object.
in FaceView.h -
@protocol FaceViewDataSource
- (float)smileForFaceView:(FaceView *)sender;
@end
@interface FaceView : UIView
then in a class that you want to conform to the delegate, you add the following to it's @interface line.
in HappinessViewController.m - (for a private delegation??)
@interface HappinessViewController()
or in HappinessViewCntroller.m - (more common way to do)
@interface HappinessViewController
We next need to declare ourselves as the delegate like;
in FaceView.h - (?? declares a property of FaceView. This allows the conforming class to ??
@property (nonatomic, weak) IBOutlet id dataSource;
We then also need to declare the new class as the delegate??
in HappinessViewController.m - the method - - (void)setFaceView:(FaceView *)faceView
self.faceView.dataSource = self;
Now the final thing to do is just implement the required methods of this delegate in the conforming class (HappinessViewController). We then implement smileForFaceView like;
in HappinessViewController.m -
- (float)smileForFaceView:(FaceView *)sender // this just convert the happiness property to +/- 1
{
return (self.happiness - 50) / 50.0;
}
{
return (self.happiness - 50) / 50.0;
}
And finally ??????;
in FaceView.m, the - draawRect method -
float smile = [self.dataSource smileForFaceView:self]; // delegate our View's data
See the next Post for implementing canned delegates;
(as always many thanks to the incomparable Paul Hegerty and his Stanford iOS lectures