views:

139

answers:

1

How do I make a delegate? I have a class called CustomSign. The class has a view associated with it. The view has 2 elements. A textfield and a uilabel. I want to copy the textfields data to the uilabel when you click the done button.

Here's my code in the CustomSign.m I don't know how to make it a delegate.

-(void)textFieldDidEndEditing:(UITextField *)textField {
    [textField resignFirstResponder];
    label.text = textField.text;
}
+2  A: 

You need to have a reference to the text field in your CustomSign.m file. This can either be an outlet which you then connect up in Interface Builder, or you can store a reference to the text field directly if you're creating it programmatically.

You then call the -setDelegate: method of the text field to assign your object as the delegate:

//in CustomSign.m
- (void)awakeFromNib
{
    //assume textField is an ivar that is connected to the textfield in IB
    [textField setDelegate:self];
}

You can also set the delegate of the text field in Interface Builder by control-dragging from the text field to your object.

Note that you should not call -resignFirstResponder yourself.

Rob Keniger
You can also use dot notation for this instead of explicitly calling the setter method: `textField.delegate = self;`
Jacob Relkin
I get the following warning message. and then the done button doesn't react the way it should.CustomSign.m:55: warning: class 'CustomSign' does not implement the 'UITextFieldDelegate' protocol
Cocoa Dev
You just need to change your class definition so that you implement the protocol: `@interface CustomSign : NSObject <UITextFieldDelegate>`
Rob Keniger