Interaction between Subview and UIViewController with Delegates - objective-c

I've read a lot of articles to get some information about the whole delegate concept in objective c. At least I think I got the general idea of that. But I didn't found an answer for my question - or I just found it but didn't got it...
In my case I got a custom subview I'm adding programmatically on my UIViewController. I want to have an interaction from the custom UIView to call some methods of the controller. I think it would be better to have a delegate concept instead of making a reference to my UIViewController in the SubView, right?
My question is, isn't it possible to do something with my UIScrollViewDelegate. My UIViewController is implementing some delegate methods because my SubView is a UIScrollView. So would it be possible to add a custom method which I can call with something like:
[self.delegate myCustomMethodOnUIViewController]
Or what would be the best way? Should I set up a protocol and add it as custom delegate to my UIViewController? Do I have to set up then a delegate property on my subview?
Thanks for help!
Andy

If you're adding the UIView as a subview to the UIViewController and you want to execute some methods from the superview in your subview there may be some mistake in your software design.
If there's a necessity to do it, then use the #class variable for circular inclusions and call your methods. To read more about #class directive.
http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/objectivec/Chapters/ocDefiningClasses.html
More illustration can be read at the link:
#class vs. #import
You can make it work with delegates and protocols, but make sure you handle memory properly within the same contexts to avoid leaks.

Related

Why shouldn't I subclass a UIButton?

I've asked a few questions on stack overflow about subclassing a UIButton, and a couple of people have informed me that I shouldn't subclass a UIButton.
What are the negatives of subclassing a UIButton? And I know it's vague, but what are other alternatives to subclassing a UIButton?
The Cocoa frameworks take the approach that the Object Composition pattern is more appropriate than traditional class hierarchy.
In general, this means that there is likely to be a property on UIButton where you can set another object to handle various aspects of the button. This is the preferred way to "customize" how your button works.
One of the main reasons for this pattern is that many library components create buttons and don't know that you want them to create instances of your subclass.
edit, your own factory method
I noticed your comment above about saving time when you have the same button config across many buttons in your app. This is a great time to use the Factory Method design pattern, and in Objective-C you can implement it with a Category so it's available directly on UIButton.
#interface UIButton ( MyCompanyFactory )
+(UIButton *) buttonWithMyCompanyStyles;
#end
#implementation UIButton
+(UIButton *) buttonWithMyCompanyStyles {
UIButton *theButton = [UIButton buttonWithType:UIButtonTypeCustom];
// [theButton set...
return theButton;
}
#end
It's because UIButton is kind of special in that there are a few complexities/subtleties/restrictions (i.e. additional overrides for you to define, notably +buttonWithType:) required in order for it to work as expected. It's more than the usual -initWithFrame: (and -initWithCoder:, if used in XIBs). IDK why the framework authors allowed those details to leak out into our domain, but it's something that must be dealt with by us now. The restriction is that your implementation must not depend on (i.e. extend) preset system button styles; You must assume UIButtonTypeCustom as your starting point for a UIButton subclass.
On implementing a subclass of UIButton
If you are just looking for something more lightweight with your own 'subviews' you should instead be subclassing UIControl. UIButton subclasses UIControl and can handle events, like:
[mySubclassedButtonFromUIControl addTarget:self action:#selector(_doSomething:) forControlEvents:UIControlEventTouchUpInside];
UIControl subclasses UIView so you can cleanly layoutSubviews on any views contained by your UIControl subclass and avoid unnecessary views that come with UIButton. In essence you are just creating your own 'UIButton' but you avoid having to work around behavior and functionality you don't really want or need.

How to set delegate for subclass

I'm writing own switch class. I'd like to add a delegate to it - examplary if we have UIImagePickerController we add UIImagePickerControllerDelegate to #interface of some viewcontroller and we can set methods like imagePickerControllerDidCancel:(UIImagePickerController *)picker...
I want to do something similar for my class - it's named HSwitch, so I want to add HSwitchDelegate to #interface of some view controller.
I would like to add to this delegate a method valueWasChanged, that I could set in viewController and which would be called each time when slider changes value.
How can I do that? I didn't do it yet, so... please help me :)
Thanks!
If your class is a switch, presumably it inherits from UIControl. If this is the case, don't introduce the complexity of delegates - use target-action instead, and send actions / register targets as you would with any other control. See the UIControl class reference for details. UIControlEventValueChanged would be a suitable event for your needs.

Call method in UITableViewController from custom UITableViewCell

I need to call a method and pass an object from my custom UITableViewClass implementation to my UITableViewController class. I realize creating an instance of the tableViewController in the custom tableViewCell and calling tableViewController's method is a bad practice.
What is the proper way of doing this?
Two magical concepts in Objective-C are Delegation and Notifications.
Delegation allows you to have your controller hook into a weak object referenced in the cell, which avoids a retain cycle, while still allowing you to send messages to it.
Notifications allow your Cell to broadcast a general notification to any classes that are active and listening for it.
Pick one, and whichever is easiest, stick with it. The two are basically equal in this situation.
Having a reference of the tableController inside the cell is indeed Bad practice
You could fix this by implementing a special #protocol for your UITableViewClass
And add a delegate method to it, and then implment the method inside UITableViewController, and since your UITableViewClass delegate is your UITableViewController, then you would call it like
in your UITableViewClass.m
[delegate someMethod:data];

Objective C View to Controller Communication

What is the proper way to accept user input in a view and then transfer it to that view's controller? I know the NotificationCenter is one option, but surely there is a more elegant way to transfer data from a view to its controller?
All help is greatly appreciated and I always accept an answer!
Use the delegate protocol design pattern, or target-action by subclassing UIControl. Think about how a UIButton tells a view controller that it's been pressed. In interface builder, you connect an action - a selector something like touchUpInside: to a target - the view controller that owns it. In non-IB, you directly tell the UIButton what selector and what target to use.
Both methods make sense in different cases. For a UITextField, for example, it makes more sense to use delegation because it's possible for the text field to send you any number of events, such as an event when the user begins editing, ends editing, or types a character.
For a button, it makes more sense to use target-action because there's really only one event expressed in different forms.
For swipes and drags and other gestures, use UIGestureRecognizers.
You're looking for Delegation or a Data Source. You can see more information about this here, Delegation and Data Sources
A brief example of this would be, something along the lines of this:
//MyViewSubclass.h
#protocol MyViewSubclassDelegate
//Implement your delegate methods here.
-(void)didTouchView;
#end
#interface MyViewSubclass {
id<MyViewSubclassDelegate>delegate;
}
#property(nonatomic,assign)id<MyViewSubclassDelegate>delegate;
Of course, #synthesize your delegate in MyViewSubclass.m
Now in the class's header, that you want the delegate of MyViewSubclass to be, you need to conform to the `MyViewSubclassDelegate Protocol.
#import "MyViewSubclass.h"
#interface MyViewController : UIViewController <MyViewSubclassDelegate>
In your #implementation of MyViewController., implement the MyViewSubclassDelegate method of -(void)didTouchView.
When you initialize and create your MyViewSubclass object, you set MyViewController as the delegate:
myViewSubclass.delegate = self // Self being MyViewController.
In your MyViewSubclass, when you're ready to forward any information, or simply want to fire a method you would do [self.delegate didTouchView]
Hope this helps !
You are looking for delegation, where the controller set itselfs as the delegate of the view. You know it from UITableViewDelegate.
Make your view a subclass of UIControl and implement the target/action design pattern - use the sendActionsForControlEvents: method to message the controller.
Often the UIKit objects like UITextField have delegate methods that you can implement to perform your business logic. E.g UITextField has a delegate method called - textFieldDidEndEditing: that gets called after the user has dismissed the keyboard.

What invokes viewDidLoad when subclassing UIViewController?

Trying to get my head around protocols and delegates when extending it further into the UIKit framework's implementation.
From my understanding of this stackoverflow post a delegate method will usually have Did, Should & Will in it's name.
Based on this, I would assume that - (void)viewDidLoad; declared in UIViewController.h is a delegate method, but of what and from where?
I've looked at UIViewController's header file and it only adhere's to the NSCoding protocol which is a dead end. UIViewController's superclass UIResponder is also a dead end as far as I can see.
I've used viewDidLoad as an example here but this could apply to any of the Did, Should & Will methods in UIViewController.
Is this simply one of those cases that is an exception to the guidelines or am I missing something?
"did", "should", and "will" are words usually used to describe when a method is called, whether it is asking if it "should" do something", giving you a hook to run code before something "will" happen, or as a callback when something "did" happen. these words are usually used in delegate and callback methods.
viewDidLoad is called when your .nib file has been loaded into memory, and your IBOutlets have been instantiated and hooked up, and are ready for configuration. you don't need to worry about calling it yourself if you intend to subclass UIViewController, if that's what you're wondering.