How would you implement a dataSource object for an UIScrollView? - iphone

Tell me if I am wrong with that:
I made an new class ScrollViewDataSource. That class conforms to an protocol I created within my delegate for the scroll view. Well, it's a very special delegate that does some very complex stuff upon scrolling. So this delegate receives that data source object upon initialization. The datasource object now has a method
(NSArray*)subviewsFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex;
so when the user scrolls, the delegate rings the datasource object lots of times dunring scrolling to ask for data. I'm going to recycle views during scrolling. That means, if the user scrolls down, I remove the views from the top to the bottom, and fill them up with new data.
The NSArray contains UIView objects, which will be positioned appropriately during scrolling. Also, on first launch of the view that contains the scroll view, the data source will deliver the data to display the first visible contents.
Is that a good pattern, or do you have better ideas for that?
BTW: I know a UITableView does something similar. But I want to learn that. It's a practise for me. Thanks!

May,
This is the best pattern that you can make use of. Exclusively followed by Apple in various of their data displaying views like UITableView in iPhone and NSTableView,NSOutlineView in Mac.
All the best.

If your content views are using same layout, I would make ScrollViewDataSource containing only the data that content views needed, so I don't need to alloc/create new UIView for my UIScrollView when asking new data (since MyScrollView hold the content views that I can reuse):
#interface MyScrollView : UIView {
#private
id <MyScrollViewDelegate> _delegate;
id <MyScrollViewDataSource> _dataSource;
UIScrollView *_scrollView;
NSMutableArray *_contentViews; // you need to create/maintain/reuse contentView from here
}
#property (nonatomic, assign) id <MyScrollViewDelegate> delegate;
#property (nonatomic, assign) id <MyScrollViewDataSource> dataSource;
#end
#protocol MyScrollViewDataSource <NSObject>
#optional
- (NSString *)myScrollView:(MyScrollView *)myScrollView requestTitleForContentViewAtIndex:(NSInteger)index;
- (UIImage *)myScrollView:(MyScrollView *)myScrollView requestLogoForContentViewAtIndex:(NSInteger)index;
#end
...
The good about this is, your MyScrollView interface would look clean to superview, and you are dealing all the scrolling, layout, redraw and content updating stuffs within your MyScrollView AND without bothering other views or controllers from outside.
But, if your content views are totally different to each others, I won't use pattern like this.

Related

Subclass UIViewController or create a custom NSObject when the view is not fullscreen

I need to create a class controller to manage the behavior of a custom view I created.
The standard approach is to subclass UIViewController, but in my case I instead decided to
subclass the NSObject essentially for three reasons:
my view needs to be added as small subview of the main view controller (it will not be displayed using something like presentModalViewController or pushViewController...) and it does not require any kind of toolbar or navigation control inside of it
Most probably my controller will not need to be notified for device orientation because its view will be always used in portrait format, so I'm not interested to receive the usual rotation messages willRotateToInterfaceOrientation etc...
I need to keep this class as lightweight as possible minimizing memory consumption. Not subclassing UIViewController have the advantage to obtain a lighter class without a bunch of methods that I will never need to use
The interface of my controller is pretty simple, example:
#interface MyScrollTabBarController : NSObject <MyTabBarViewDelegate> { }
/**
* The view is created internally by the controller and the client class
* can access to it in readonly mode
*/
#property (nonatomic, readonly) UIView *view;
/**
* A Property to change the view appearance
*/
#property (nonatomic, assign) MyScrollTabBarViewState viewState;
/**
* Others properties used to construct the view's subviews
*/
#property (nonatomic, retain) Location *rootLocation;
#property (nonatomic, readonly, retain) Place *place;
/**
* Designated initializer
*/
- (id)initWithPlace:(Place *)aPlace;
- (void)setRootLocation:(Location *)location animated:(BOOL)animated;
#end
To display its internal view from the parent view controller, I will use something like this:
tabBarController = [[MyScrollTabBarController alloc] initWithPlace:aPlace];
tabBarController.viewState = MyScrollTabBarViewStateXX;
tabBarController.view.frame = CGRectMake(...);
[self.view addSubview:tabBarController.view];
I'd like to know what do you think about my choice, if you think that there could be drawbacks in it and what do you usually do when you need to write a controller for a view which is not fullscreen like mine.
Thanks
Yes, this is the correct approach.
UIViewControllers are specifically for controlling full-screen views, not for sub-screens. In iOS5 there is a mechanism for composing sub-screen viewcontrollers in this way, but that's not available in iOS4 without lots of hackery.
In cases where the view and controller are inherently coupled, you could also consider making a custom view subclass that is its own controller, so for example you could have a self-contained table view subclass that managed its own data and could just be dropped into a page.
I think this is an acceptable solution.
Another solution would be creating a "fat" view that does its controlling itself (like, for instance, MKMapView, UITextView etc.). This might make things a little more manageable, and if the view is very specialized, and its controller is intended to only work with this one class of view, you don't really lose any reusability (because there isn't much).
what do you usually do when you need to write a controller for a view which is not fullscreen like mine
It is not important that your view is not displayed full screen. It is possible (and usual) to have views consisting of subviews which each have their own controller.
I need to keep this class as lightweight as possible minimizing memory consumption. Not subclassing UIViewController have the advantage to obtain a lighter class without a bunch of methods that I will never need to use
Subclassing UIViewController does not consume an unreasonable amount of memory, so this should not be part of the consideration.
[...] if you think that there could be drawbacks in it [...]
With your solution you loose flexibility. It is likely that you will reuse your solution in a context where you need to respond to UILifecyle-Messages or use other UIViewController features.
If your views shall be lightweight you could consider using a UIView subclass and use a delegate for the logic behind your view.
Hi You are subclassing NSObject and declaring a UIView inside it
#interface MyScrollTabBarController : NSObject <MyTabBarViewDelegate> { }
#property (nonatomic, readonly) UIView *view;
I Suggest you should subclass UIView, so you will not have to declare an additional view object.
so instead of self.view you can simply refer as self
tabBarController = [[MyScrollTabBarController alloc] initWithPlace:aPlace];
tabBarController.viewState = MyScrollTabBarViewStateXX;
tabBarController.frame = CGRectMake(...);
[self.view addSubview:tabBarController];

Same UIView subclass in several UIViewController subclasses?

I have several UIViewControllers. I would like to use the same UIView subclass (which goes on top of the existing UIViewController's view) in all of them. Is this possible using Interface Builder?
I mean, I would like to be able to drag a UIView onto each UIViewController's view, and rename the class of this dragged UIView to CustomView, and all the elements within the CustomView would show up... is this possible?
Based on your question and your response to highlycaffeinated — whose answer is correct but I think may be slightly askew from what you're asking — I think you want to be able to design a view graphically within Interface Builder (so, you haven't written a custom UIView subclass, you've just arranged some UIViews in a certain way and so that they're all children of another view), then embed it into several view controllers via some sort of indirect reference, so that you're not copying and pasting the same user interface elements and if you make a change in one place, that change then takes effect everywhere?
As far as I'm aware, there's no built-in facility in Interface Builder or Xcode 4 for achieving that. XIBs are pure data and UIViews don't have the smarts to handle an out-of-file reference.
What you can do is design the view you want to use in one XIB, called say ReusableView.xib, then write a custom UIView subclass that looks something like:
#implementation ReusableViewTemplate
- (id)initWithCoder:(NSCoder *)aDecoder
{
// initialise ourselves normally
self = [super initWithCoder:aDecoder];
if(self)
{
// load everything in the XIB we created
NSArray *objects = [[NSBundle mainBundle]
loadNibNamed:#"ReusableView" owner:self options:nil];
// actually, we know there's only one thing in it, which is the
// view we want to appear within this one
[self addSubview:[objects objectAtIndex:0]];
}
return self;
}
#end
Then, in your NIBs put in a UIView where you want the reusable view to go, and set the 'class' to 'ReusableViewTemplate' or whatever you called it.
If you open the ReusableView XIB and set the type of the parent view to ReusableViewTemplate, then you can wire up any UIControls (such as buttons or switches) to connect to there. You'll probably want to define some custom protocol for your reusable view template and catch viewDidLoad in any view controllers that use the reusable view in order to set an appropriate delegate.
EDIT: further thoughts on this. I've created an example project (currently at a generic file sharing site, so may not survive forever) with a class ReusableView that, for the purpose of example contains a segment view and a button, and looks like this:
#implementation ReusableView
/*
initWithCoder loads the relevant XIB and adds its
only object, which is a UIView, as a subview of this
one. If you don't like the double hierachy, you
could just have a list of views in the XIB and
addSubviews:, but then it'd much more difficult to
edit the thing graphically. You could strip the top
view programmatically, but this is just a simple
example, so...
*/
- (id)initWithCoder:(NSCoder *)aDecoder
{
// initialise ourselves normally
self = [super initWithCoder:aDecoder];
if(self)
{
// load everything in the XIB we created
NSArray *objects = [[NSBundle mainBundle]
loadNibNamed:#"ReusableView"
owner:self
options:nil];
// actually, we know there's only one thing in it, which is the
// view we want to appear within this one
[self addSubview:[objects objectAtIndex:0]];
}
return self;
}
#synthesize delegate;
#synthesize segmentedControl;
#synthesize button;
/*
NSObject contains machinery to deal with the possibility
that a class may be sent a selector to which it doesn't
respond.
As of iOS 4, forwardingTargetForSelector: can be used to
nominate an alternative target for the selector quickly.
In previous versions of iOS, or in iOS 4 if you don't
respond to forwardingTargetForSelector:, you may take
delivery of the problematic invocation and deal with it
yourself.
Dealing with the invocation costs more than providing
a forwarding target for the selector, so its worth having
both.
If you're only targeting iOS 4 or above, you needn't
keep the implementation of forwardInvocation: below.
What we're doing is declaring a bunch of IBActions so
that we can wire changes up to them in Interface Builder.
By failing to implement them and providing the delegate
as the thing to talk to for any selectors we don't know,
we're allowing those wirings to be as though assigned
to the delegate.
*/
- (id)forwardingTargetForSelector:(SEL)aSelector
{
return delegate;
}
- (void)forwardInvocation:(NSInvocation *)anInvocation
{
[anInvocation setTarget:delegate];
[anInvocation invoke];
}
#end
With interface:
#interface ReusableView : UIView
{
IBOutlet id delegate;
IBOutlet UISegmentedControl *segmentedControl;
IBOutlet UIButton *button;
}
#property (nonatomic, assign) id delegate;
#property (nonatomic, assign) UISegmentedControl *segmentedControl;
#property (nonatomic, assign) UIButton *button;
/*
NB: we're not actually going to implement these. We're
declaring them for the benefit of Interface Builder / Xcode 4.
What we'll actually do is, any time we receive a selector
we don't implement, hand it off to the delegate. So it's a
quick way of avoiding writing any glue code to pass messages
from this little reusable view to its delegate.
A better alternative could define a formal protocol that
forwards both the changed control and self from the
reusable view to its delegate. But that's obvious and
verbose, so has been omitted for the purposes of example.
The implementation as stands will generate compiler warnings,
but such is life. To get rid of the warnings, comment out
the two following lines, but only AFTER you've wired
everything up in Interface Builder / Xcode 4. They're left
uncommented here to help draw attention to the point about
selector/invocation forwarding that you'll see in the
#implementation.
!!!!!!!!!!!!!!!
HENCE:
delegates MUST implement the following methods.
!!!!!!!!!!!!!!!
We could work around that by checking at runtime whether
the actual delegate implements them and forwarding to
a dummy object that implements them to do nothing otherwise,
but that's slightly beyond the point of the example.
*/
- (IBAction)reusableViewSegmentControlDidChange:(id)sender;
- (IBAction)reusableViewButtonWasPressed:(id)sender;
#end
Net effect is that if a view controller has a UIView of type ReusableView within a XIB, it gets the contents of ReusableVew.xib inserted at runtime. If it wires itself up as the delegate of ReusableView within Interface Builder / Xcode 4 and implements:
- (IBAction)reusableViewSegmentControlDidChange:(id)sender;
- (IBAction)reusableViewButtonWasPressed:(id)sender;
Then it gets the messages from the embedded views.
This is achieved very simply and very neatly in Objective-C by using NSObject's inherent ability to forward selectors (as of iOS 4) or invocations (in earlier versions, at a greater cost) that it doesn't implement rather than allow an exception to occur.
Yes, it's possible. Just as you could have (for instance) multiple UIViewControllers in your project, each with a UIImageView as a view, you can do the same with your own subclasses of UIView.

Cant load UITableView

Ok, this is really really easy, but even though I went through 100s of tutorials, I still have no idea whats wrong with my app. All I want to do is just to display a table view, even empty, but I get a black screen on the simulator and an exception in the output too.
This is what I did (followed step by step a few tutorials):
Open a view based app
This is my header:
#interface TableViewsViewController : UIViewController <UITableViewDelegate> {
IBOutlet UITableView *tblSimpleTable;
}
#property (nonatomic, retain) IBOutlet UITableView *tblSimpleTable;
#end
did not do anything in .m besides synthesizing.
IB: made 3 connections: delegate, dataSource, and tblSimpleTable to File's owner.
Yes, I am a beginner, but this is ridiculous...appreciate any help. Thanks!
First off, a table view has two "delegate" types -- the table view delegate and the table view data source. Your interface is being a delegate, but not a data source, for the table view.
If you add UITableViewDataSource to the interface, i.e.
#interface TableViewsViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
and then compile, you'll probably get errors about missing methods for number of sections and for cell. After you add these to your implementation, the table view should work.
My guess is the table view tries to ask your class for number of sections in the table, and since your class doesn't actually respond to that selector, the code crashes.
Add
tblSimpleTable.delegate = self
in viewDidLoad
...and ensure you have connected it correctly in interface builder.

Memory question: taking ownership of a subview

If I have a subview built in Interface Builder, and I want to give it an actual name, I presume the only way to do this is to create a UIView instance variable in my view controller, and then do something like this:
- (void)viewDidLoad
{
[super viewDidLoad];
self.moveView=[self.view.subviews objectAtIndex:0];
self.moveView.backgroundColor=[UIColor redColor];
}
In so doing, I can now work with this subview using a conventional name, "moveView," rather than addressing it by its index number within the view heirarchy.
Is this is good way of doing something like this (outside of actually using a custom view class)?
Another way that is perhaps easier and does not require that you figure out the index number seems to be just creating a UIView #property IBOutlet and assigning that to the Interface Builder and doing this:
#property (nonatomic, retain) IBOutlet UIView * sensitivity;
in #interface.
However, I want to know if the "retain" quality of this #property means that my UIView is essentially using up double the memory, since doesn't the Interface Builder UIView also store this in memory? Or will hooking this up in IB make these one and the same, with just a singe actual UIView instance?
Yes, IBOutlets are a much better idea than referencing subviews by their index.
retain doesn't cause a property to copy an object on set—that's what the copy attribute is for—it just increments the object's retain count to "claim" it. I highly recommend reading the iOS Memory Management Guide if you haven't yet. Also note its section on nibs.

iPhone Views at Runtime?

I am new to the iPhone SDK and am trying to create 3 views and switch between them. Data will come from a server and I will basically be showing 1 view and caching the other two. So far I am just trying to create a view and display it at run-time. My code is listed below. It shows only a blank screen and I think I am missing a key concept. Any Help?
#import <UIKit/UIKit.h>
#import "ImageViewController.h"
#interface Test5ViewController : UIViewController
{
IBOutlet UIView *rootView;
ImageViewController *curImage;
ImageViewController *nextImage;
ImageViewController *prevImage;
}
#property(nonatomic,retain) IBOutlet UIView *rootView;
#property(nonatomic,retain) ImageViewController *curImage;
#property(nonatomic,retain) ImageViewController *nextImage;
#property(nonatomic,retain) ImageViewController *prevImage;
#end
and
- (void)loadView
{
self.curImage = [[ImageViewController alloc]initWithNibName:#"ImageView" bundle:[NSBundle mainBundle]];
UIImage *pic = [UIImage imageNamed:#"baby-gorilla.jpg"];
[self.curImage assignImage:pic];
self.rootView = self.curImage.view;
}
and
#import <UIKit/UIKit.h>
#interface ImageViewController : UIViewController
{
IBOutlet UIImageView *image;
}
-(void)assignImage:(UIImage *)screenShotToSet;
#property(nonatomic,retain) IBOutlet UIImageView *image;
#end
Welcome to the iPhone SDK!
In general, there are two ways to get any view displayed.
First, and most commonly, you use a NIB file created by the Interface Builder. This is usually the easiest way to get started and I would recommend it for what you're trying to do here. It's too lengthy to describe all the steps you need to do for what you have here, but basically start in xcode by creating a new file and selecting "user interfaces" and choose View XIB. This will create a basic NIB file (they're called NIBs rather than XIBs for historical reasons). The first step in interface builder is to change the class name of the "File's Owner" to your UIViewController subclass (Test5ViewController). You can then drop anything that IB will allow into the view window or even replace the pre-supplied view object with one of your own. And here's the trick: make sure the view outlet (supplied by the UIViewController superclass) is connected to a view. Once this is done, this view will be automatically loaded when your NIB is loaded. You can then just put your UIViewController subclass (Test5ViewController) in your MainWindow.xib NIB file to get it automatically loaded, and you're in business.
Now, the way you're doing it here is the second way. Some people like to code this way all the time and not user interface builder. And while it's definitely necessary sometimes and always more flexible, it makes you understand what is happening a bit better. There may be other things, but the main thing you're missing is that in your code above, you have nothing that is adding your view into the view hierarchy. You need to check first that you have an UIApplicationDelegate subclass and it needs to load your "root" UIViewController class. All initial project creation types in xcode do this (except Window-based application). It is code like:
[window addSubview:rootController.view];
Once this is done, if your view controller wasn't loaded by the NIB (described briefly above), your loadView method will be called, expecting you to build your own view hierarchy. Above, you created the view(s), but failed to put them in a hierarchy. You need something like:
[self.view addSubview:curImage.view];
No view will be rendered until added to the view hierarchy. Make sure to look up the UIView class in the documentation and understand the variety of ways to add and remove views to the view hierarchy.
A couple things I should warn you about:
* your code above is leaking. You need to review how objective-C properties work. There's lots on this site about it. More than I have time to write about here.
* don't create a rootView property in the case you have here. There already is one in the superclass (UIViewController). It's just 'view'. Use that for saving your root view.
I hope this helps you get started. It can be bewildering at first, but you'll soon get it going! I recommend building and rewriting and rebuilding a lot of sample code before you do your "real" application. The SDK has many great samples.