Custom Cocoa touch control and initialization - ios

I have designed a nice custom control CustomUIView as a subclass of UIview, with a nice initialiser that takes in 8 parameters. I made it to be the designated initializer to make sure, any user will provide all the 8 parameters correctly.
After few days, I wanted to reuse that control in a different project where nibs are used.
I added a basic UIView into the canvas of one of the NIBs and changed The Custom class option to my CustomUIView class. But I immediately realised my nice initializer is of no use, since it is not called at all.
What would you recommend to do about this? I want to ensure that
all the parameters are taken in but at the same time
I want basic positioning of that custom control in IB.

Why not build on top of the standard UIViewController initializer for NIBs then?
- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle parameter1:(id)param1...
NSAssert(param1 != nil && param2 != nil ...);
if (self = [super initWithNibName:nibName bundle:nibBundle]) {
//Custom initializations here.
}
return self;
}

Related

Conceptual q about custom UIKit objects

Simple question: what is the standard method of creating a customized version of say a UILabel, UIButton, etc. such that I can easily use it in multiple places? Is it simply to extend the appropriate class:
import UIKit
class FormField: UITextField {
override init()
{
super.init()
// borderStyle = UITextBorderStyle.None
}
}
Basically just want to get some default values set for some UI objects so I can easily drop them into the interface when necessary. Not really sure how to get this working.
It is very rare to subclass something like UILabel.
The most common approach is a HAS-A pattern, where you let a controller (often a UIViewController) manage the view for you and you reuse that. Alternately, you may make a UIView that contains the view you want to customize, and customizes it for you (passing along things that need to be passed along).
You can also have a "configure my view this way" function that you can call on an existing standard view. I haven't seen this very often in reusable code. My experience is that these kind of configuration functions turn out to be very app specific, but they're reasonable common.
Things like UITextField have delegate methods already, and a common way to customize them is to create a reusable delegate that applies certain behaviors.
It depends of course on what you're trying to achieve, but subclassing is pretty far down on the list of patterns, unless it's a class explicitly designed and documented to be subclassed (like UIView or UIViewController).
UIView and its subclasses have two designated initializers, -initWithFrame: and -initWithCoder:. The first is for programmatic instantiation while the latter is for views being unpacked from a Storyboard or NIB. Because of this, the common pattern for subclassing UIView subclasses is the following (I'm using ObjC but the Swift code should be easy to figure out):
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if(self) {
[self commonInit];
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if(self) {
[self commonInit];
}
return self;
}
- (void)commonInit {
// Do your special setup here!
}
Then, if you're using the views in Interface Builder, go to the Identity tab on the right-assistant-editor-sidebar, and in the top box where it says UILabel or UIButton, put in your custom button class name.
Hopefully this clears things up a bit.

Explain data management of storyboards?

I have this UIImageView in one of my view controllers
I've set it as a subclass of this cutsom UIImageView, ABProfileImageView
Here's that ProfileImageView class:
#import "ABProfileImageView.h"
#implementation ABProfileImageView
-(id)init {
self = [super initWithImage:[UIImage imageNamed:#"X4Hibreb.jpeg"]];
if (self) {
self.image = [UIImage imageNamed:#"X4Hibreb.jpeg"];
}
return self;
}
#end
and I have an image name X4Hibreb.jpeg in the project folder,
So I'm not sure why the imageview doesn't have the picture I set it to be? I think it's some higher understanding thing that I don't get, I usually do programmatic UI's, this is the first time I'm using a storyboard.
You have implemented init, however you also need to implement initWithCoder:, which is the initializer called when decoding objects from NIB files and storyboards.
Usually a good practice is to move common code from init and initWithCoder: to a _commonInit method and call it in the init.
You need to initialize the imageview.

How to initialize a custom view(controller) so it works both programmatically and in Interface Builder?

Suppose you implement a custom table view and a custom view controller (which mostly mimics UITableViewControllers behaviour, but when initialized programmatically, ...
#interface Foo : MyCustomTableViewController ...
Foo *foo = [[Foo alloc] init];
... foo.view is kind of class MyCustomTableView instead of UITableView:
// MyCustomTableView.h
#protocol MyTableViewDelegate <NSObject, UITableViewDelegate>
// ...
#end
#protocol MyTableViewDataSource <NSObject, UITableViewDataSource>
// ...
#end
#interface MyCustomTableView : UITableView
// ...
#end
// MyCustomTableViewController.h
#interface MyCustomTableViewController : UIViewController
// ...
#end
How should you implement/override init methods in correct order/ways so that you could create and use an instance of MyCustomTableView both by subclassing MyCustomTableViewController programmatically or from any custom nib file by setting custom class type to MyCustomTableView in Interface Builder?
It important to note that this is exactly how UITableView (mostly UIKit for that matter) works right now: a developer could create and use either programmatically or by creating from nib, whether be it File owner's main view or some subview in a more complex hierarchy, just assign data source or delegate and you're good to go...
So far I managed to get this working if you subclass MyCustomTableViewController, where I will create an instance of MyCustomTableView and assign it to self.view in loadView method; but couldn't figure out how initWithNibName:bundle:, initWithCoder:, awakeFromNib, awakeAfterUsingCoder:, or whatever else operates. I am lost in life cycle chain and end up with a black view/screen each time.
Thanks.
It is a real mystery how the UITableViewController loads its table regardless of if one is hooked up in interface builder, however I have came up with a pretty good way to simulate that behavior.
I wanted to achieve this with a reusable view controller that contains a MKMapView, and I figured out a trick to make it happen by checking the background color of the view.
The reason this was hard is because any call to self.view caused the storyboard one to load or load a default UIView if didnt exist. There was no way to figure out if inbetween those 2 steps if the user really didn't set a view. So the trick is the one that comes from a storyboard has a color, the default one is nil color.
So now I have a mapViewController that can be used in code or in storyboard and doesn't even care if a map was set or not. Pretty cool.
- (void)viewDidLoad
{
[super viewDidLoad];
//magic to work without a view set in the storboard or in code.
//check if a view has been set in the storyboard, like what UITableViewController does.
//check if don't have a map view
if(![self.view isKindOfClass:[MKMapView class]]){
//check if the default view was loaded. Default view always has no background color.
if([self.view isKindOfClass:[UIView class]] && !self.view.backgroundColor){
//switch it for a map view
self.view = [[MKMapView alloc] initWithFrame:CGRectZero];
self.mapView.delegate = self;
}else{
[NSException raise:#"MapViewController didn't find a map view" format:#"Found a %#", self.view.class];
}
}
The strategy I've used when writing such classes has been to postpone my custom initialization code as late as possible. If I can wait for viewDidLoad or viewWillAppear to do any setup, and not write any custom code in init, initWithNibName:bundle: or similar methods I'll know that my object is initialized just like the parent class no mater what way it was instantiated. Frequently I manage to write my classes without any overrides of these init methods.
If I find that I need to put my initialization code in the init methods my strategy is to write just one version of my initialization code, put that in a separate method, and then override all the init methods. The overridden methods call the superclass version of themselves, check for success, then call my internal initialization method.
If these strategies fail, such that it really makes a difference what way an object of this class is instantiated, I'll write custom methods for each of the various init methods.
This is how I solved my own issue:
- (void)loadView
{
if (self.nibName) {
// although docs states "Your custom implementation of this method should not call super.", I am doing it instead of loading from nib manually, because I am too lazy ;-)
[super loadView];
}
else {
self.view = // ... whatever UIView you'd like to create
}
}

Is there a init method in iOS that is always called?

Is there a method that is always called in Cocoa? Many classes have init or initWith, but even worse they can be loaded from a nib or something. I don't want to have to scrape around and find how it does this in this case. I just want to set some initial variables and other things, and I want a method to subclass that I can depend on no matter if it's a UIView, UIViewController or UITableViewCell etc.
No there is not such a method. init comes from NSObject so every object can use it, and as well subclasses define their own initialization methods. UIView, for example, defines initWithFrame: and furthermore there are init methods from protocols, such as NSCoding which defines initWithCoder:. This is the dynamic nature of objective-C, anything can be extended at any time. That being said, there are some patterns. UIViewController almost always takes initWithNibName:bundle: and UIView almost always takes initWithFrame: or initWithCoder:. What I do is make an internal initialize method, and just have the other inits call it.
- (void)initialize
{
//Do stuff
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if(self)
{
[self initialize];
}
}
- (id)initWithCoder:(NSCoder *)aCoder
{
self = [super initWithCoder:aCoder];
if(self)
{
[self initialize];
}
}
Not 100% sure that it is always called, but I am pretty sure that this is a viable option. To be perfectly honest, I can't recall that I have ever seen this method used in practice and I usually shy away from using this method (I have absolutely no idea why, probably because it's just not the cleanest and most comprehensive method to achieve this...):
-didMoveToSuperview()
From documentation:
Tells the view that its superview changed.
The default implementation of this method does nothing. Subclasses can override it to perform additional actions whenever the superview changes.
There's many ways you can write a custom initializer.
- (id)initWithString:(NSString *)string {
if((self == [super init])) {
self.string = string;
}
return self;
}
That's just how I write my initializers in general. For example, the one above takes a string. (you don't have to pass strings if you don't want).
Btw, init is a method. According to the header for NSObject, init has a method implementation.

Static content in UITableView - Problems with Apples guide

I have been following the guide from Apple:
http://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/TableView_iPhone/TableViewCells/TableViewCells.html#//apple_ref/doc/uid/TP40007451-CH7
concerning: Technique for Static Row Content.
My problem is the following:
All my cells are nil.
According to Apple, the loading of the view should instantiate all object populating that nib file, bit only the tableview is instantiated. Thus the cell are nil and crashes the program in method cellForRowAtIndexPath: when it is returning a NULL cell.
I have followed the guide to the letter, search all over and have found no solution, except creating a nib for each cell and loading those ones when needed, but that solution is much less elegant than the Apple solution.
Any help would be appreciated.
You have probably not bound your IBOutlets for the cells to the cells themselves. If your cell ivars are nil, then you didn't wire something.
EDIT
If the IBOutlets are connected, but the ivars are nil, then the IBOutlets aren't connected. There other possibilities, but that's the most common. Other possibilities: you're trying to access prior to viewDidLoad. In particular, you can't access your ivars during initWithFrame:. Other possibility is that you're overwriting them at some point. Check their values in viewDidLoad. Other possibility is that you're loading the wrong nib file, or not loading a nib file at all. All possibilities, but I'd first check everything in viewDidLoad and double-check you're connections.
When instantiating your table view controller, in your init method you should call the overridden designated initializer of the superclass ([UIViewController initWithNibName:bundle:]), passing in the nib name:
- (id)init {
return [self initWithNibName:NSStringFromClass([self class]) bundle:[NSBundle mainBundle]];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization here
}
return self;
}
For more details, see this answer: Automatically Loading XIB for UITableViewController

Resources