Implementation of protocols and the delegation mechanism
suggest changeSuppose you have two views, ViewA and ViewB.
An instance of ViewB is created inside ViewA, so ViewA can send messages to that ViewB. For the reverse, ViewB needs a delegate so it can send messages back to ViewA.
Follow these steps:
- In
ViewBcreate protocol as
@protocol ViewBDelegate
-(void) exampleDelegateMethod;
@end
- Declare the delegate in the sender class
@interface ViewB : UIView
@property (nonatomic, weak) id< ViewBDelegate > delegate;
@end
- Adopt the protocol in Class ViewA
@interface ViewA : UIView <ViewBDelegate>
@end
- Set the delegate
-(void) anyFunction
{
// create Class ViewB's instance and set the delegate
[viewB setDelegate:self];
}
- Implement the delegate method in class
ViewA
- (void)exampleDelegateMethod
{
// Called by the ViewB instance.
}
- Use the method in class
ViewBto call the delegate method as
-(void) callDelegateMethod
{
[self.delegate exampleDelegateMethod];
// Messaging nil is a no-op, so a missing delegate does not raise.
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents