Reputation: 9698
I have a custom UIView I use for displaying a popover (on iPhone). In the popover are some UIButtons that I need to call methods from the ViewController's class (NOT the UIView's class, but the View that is showing the UIView).
How do I properly set this up?
UIView Button Code located in Custom UIView class:
UIButton *logoutButton = [UIButton buttonWithType:UIButtonTypeCustom];
[logoutButton setTitle:@"Logout" forState:UIControlStateNormal];
[logoutButton setFrame:CGRectMake(0, 0, content.frame.size.width, 44)];
[logoutButton addTarget:self.superview.superview action:@selector(logout) forControlEvents:UIControlEventTouchUpInside];
[logoutButton setBackgroundImage:redImage forState:UIControlStateNormal];
[logoutButton setBackgroundImage:redImageHighlight forState:UIControlStateHighlighted];
[logoutButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[content addSubview:logoutButton];
Upvotes: 0
Views: 1534
Reputation: 9698
Ok so I do believe that creating a custom delegate is the PROPER way to handle this problem. However, I did discover that this method works correctly (not sure if it is "proper" though)
[logoutButton addTarget:self.superview action:@selector(logout) forControlEvents:UIControlEventTouchUpInside];
This seems to tell the button to use the class (ViewController) of it's superview (UIView). Again, not sure if this is the proper/correct way to call a method from the main view controller, but it works without a problem so it seems useable.
Upvotes: 0
Reputation: 82209
The best way to do this is to use the delegate pattern in your UIView subclass to notify the owner when your logout button is pressed. When you create the instance of your view in your viewcontroller, set the delegate to self.
Checkout 'writing custom delegates' in http://enroyed.com/ios/delegation-pattern-in-objective-c-and-writing-custom-delegates/
You can't get access to the ViewController connected to a superview in the way you've tried to do in the code above.
Alternatively, you could post a notification. E.g. send an app-wide message that a logout should be performed. Check out NSNotificationCenter for how to do this.
Something like:
[[NSNotificationCenter defaultCenter] postNotificationName:kShouldLogOutNotification object:nil];
EDIT: You'll definitely want to use a delegate in your use-case.
Upvotes: 2
Reputation: 259
This sort of thing is generally accomplished with a delegate, which is a heavily used design pattern in UIKit. See: What is the purpose of an iOS delegate?
Upvotes: 0