Tyilo
Tyilo

Reputation: 30102

Programmatically set all UITextField and UITextView's delegates to self

I have this code in -(void) viewDidLoad:

for(UIView *subview in self.view.subviews)
{
    if([subview isKindOfClass: [UITextView class]] || [subview isKindOfClass: [UITextField class]])
    {
        // error: property 'delegate' not found on object of type 'UIView *'
        subview.delegate = (id) self;
    }
}

However it get the error, which can be seen in the comment in the code above.

I know that UIView doesn't have the delegate property, however I know that the UIView is either a UITextField or UITextView, and both of these has the delegate property.

How do I fix this?

Upvotes: 1

Views: 3321

Answers (1)

bryanmac
bryanmac

Reputation: 39296

You can cast the current UIView to a text view or text field

Split the check into two so you know what type to cast it to. Another way to do it would be to see if the object responds to the selector setDelegate and if so, then send the setDelegate message to it .

So something like this:

for(UIView *subview in self.view.subviews)
{
    if([subview isKindOfClass: [UITextView class]])
    {
        ((UITextView*)subview).delegate = (id) self;
    }

    if([subview isKindOfClass: [UITextField class]])
    {
        ((UITextField*)subview).delegate = (id) self;
    }
}

Or ...

if ([subview respondsToSelector:@selector(setDelegate)])
{
    [subview performSelector:@selector(setDelegate:) withObject:self];
}

For the last one, it's less code but you need to make sure that you implement all the delegate callbacks for all UIView objects you put in your view.

Upvotes: 4

Related Questions