Swapping UITableViews in a single UIViewController - ios

I have 1 view controller where depending on the button that is clicked, a view at the bottom is swapped between 4 different table views. These table views are in their own separate UITableViewController's in the storyboard. I add the tableViews like this:
Tracks_TVC *tracksTVC = [[Tracks_TVC alloc] init];
tracksTVC.view.frame = _postView.frame;
tracksTVC.view.tag = kTagPostView;
[self.view addSubview:tracksTVC.view];
I get this error message when the code is run:
NSInternalInconsistencyException', reason: 'UITableView dataSource
must return a cell from tableView:cellForRowAtIndexPath:
I've implemented the data source in the separate UITableViewController's properly (I believe so) with all the required methods so I'm confused as to why I'm receiving this error. My only thought is that the added table view isn't using the methods in it's own UITableViewController..? Any help on this matter would be greatly appreciated!

You should create the property of TableViewController such as -
#property(nonatomic, strong) Tracks_TVC *tracksTVC;
Now in viewDidLoad initialise the same -
-(void)viewDidLoad
{
[super viewDidLoad];
self.tracksTVC = [[Tracks_TVC alloc] init];
self.tracksTVC.view.frame = _postView.frame;
self.tracksTVC.view.tag = kTagPostView;
[self.view addSubview:self.tracksTVC.view];
}
Note : Also make sure that you are returning the cell in Data source.

Related

Where to initialize subview?

I am new to iOS development and I am currently reading the book : iOS Programming (Objective C) by Big Nerd Ranch.
I am confused as in where to initialize subviews such as UIButtons, UIImageView while creating views programtically:
Should the intialization be done in the Main UIView i.e in the
initWithFrame method and maintain a additional weak reference to the subview in the UIView.
or
should I do it in the UIViewControllers loadView method and maintain a weak reference to the subview in the uiviewcontroller (Same approach used while creating UIVew using the interface builder).
I have seen both the approaches being used in various stackoverflow posts but no post that explains which approach is the right one.
you can initialize as per your app's requirement. If any view or button or anything is part of initial setup of your app then you should initialize it in viewDidload.
Now, for example there is requirement like user press button and then new view will be created then you can initialize view in button's click method etc.
So, it's depends on your requirement.
Static views which will live from start to and of app should be initialize in viewdidload, because this is the first method getting called of viewcontroller.
hope this will help :)
It dependes on which architecture you are using. Apple raises the flag of Model-View-Controller, but in fact, UIViewControllers are the View.
For Example:
Let's say that you have a pretty LoginViewController. When you instantiate it, you will be doing something like
LoginViewController *loginVC = [[LoginViewController alloc] init];
At this point, no view is loaded. Your ViewController has just executed the init method, nothing else. When the system calls
loginVC.view
the first method to be executed will be
- (void)loadView;
there you should do exactly that, load your view. So, the approach i like is to have an additional LoginView.
- (void)loadView
{
// you should have a property #property (nonatomic, strong) LoginView *loginView;
self.loginView = [[LoginView alloc] init];
self.view = self.loginView;
}
and in the LoginView init method, you should put your code to build up the view.
However, you could eliminate LoginView, and instantiate all your subviews like this:
- (void)loadView
{
self.view = [[UIView alloc] init];
UIButton *button = [[UIButton alloc] initWithTargetBlaBlaBla...];
[self.view addSubview:button];
// add more fancy subviews
}
In my experience, the first approach is much cleaner than the second one. It also makes version control a lot easier (try to merge a xib, I dare you). I always use MyView.m to build the view (a.k.a setup constriants, style) and use MyViewController.m things like animations, lifeCycle. I like to think that MyView.m is the programatic xib, so anything that you can do with xibs, you should me able to do it inside your view.
Hope it helps!!

UIPicker View subclassed not working IOS

Being new to objective-C coding I started out writing a basic app, fully programmatically (not using storyboards or xib) in one file, my AppViewController h and m files.
Everything worked lovely.
So then I wanted to break up the mass of code by subclassing sections, and everything went well apart from the UIPickerView. In fact simply commenting out the [background addSubview:colorPicker]; seemed to totally fix the issue. I never found the answer online so I proceeded to make a new document to replicate said issue.
So here goes:
UIPickerViewController.h
#import <UIKit/UIKit.h>
#import "Picker.h"
#interface UIPickerViewController : UIViewController
#end
Simply imports my new class.
UIPickerViewController.m
#import "UIPickerViewController.h"
#interface UIPickerViewController ()
#end
#implementation UIPickerViewController
- (void)viewDidLoad
{
[super viewDidLoad];
UIView *superview = self.view;
int height = superview.bounds.size.height;
int width = superview.bounds.size.width;
CGRect popupRect = CGRectMake(0, 0, width, height);
UIView *popup = [[UIView alloc]initWithFrame:popupRect];
popup.tag = 8;
[superview addSubview:popup];
Picker *picker = [[Picker alloc]initWithFrame:popupRect];
[picker viewAddTypeScreenToView:superview];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#end
Sets up a new view with a tag (so that i could reference it later with my new class)
Then actions a method from my new class to populate my new view.
Picker.h
#import <UIKit/UIKit.h>
#interface Picker : UIView
<UIPickerViewDataSource,UIPickerViewDelegate>
{
UIPickerView *colorPicker;
NSMutableArray *colorsArray;
}
#property (nonatomic, retain) UIPickerView *colorPicker;
#property (nonatomic, retain) NSMutableArray *colorsArray;
#property (strong,nonatomic) UILabel *myValue;
-(void)viewAddTypeScreenToView:(UIView*)superview;
#end
Setting up my variables and accessible method.
Picker.m
#import "Picker.h"
#implementation Picker
#synthesize colorsArray;
#synthesize colorPicker;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
}
return self;
}
-(void)viewAddTypeScreenToView:(UIView*)superview
{
UIView *baseView =[superview viewWithTag:8];
int height = baseView.bounds.size.height;
int width = baseView.bounds.size.width;
CGRect fullScreen = CGRectMake(0, 0, width, height);
UIView *background = [[UIView alloc]initWithFrame:fullScreen];
background.backgroundColor = [UIColor blackColor];
colorsArray = [[NSMutableArray alloc] initWithObjects:#"Red",#"Blue",#"Yellow",#"Green",nil];
CGRect myPickerRect = CGRectMake(10, 70, (width/2)-40, 200);
colorPicker = [[UIPickerView alloc]initWithFrame:myPickerRect];
colorPicker.dataSource = self;
colorPicker.delegate = self;
colorPicker.showsSelectionIndicator = YES;
[colorPicker selectRow:2 inComponent:0 animated:YES];
CGRect labelFrame = CGRectMake(10, 10, 180, 50);
_myValue = [[UILabel alloc]initWithFrame:labelFrame];
_myValue.textColor = [UIColor redColor];
_myValue.text = #"select colour";
[background addSubview:_myValue];
[background addSubview:colorPicker];
[baseView addSubview:background];
}
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return 1;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
return colorsArray.count;;
}
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return colorsArray[row];
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
_myValue.text = [NSString stringWithString:colorsArray[row]];
}
#end
And finally the initiation called by the method in the picker class file.
This gives me an error along these lines
-[UITableViewCellContentView pickerView:titleForRow:forComponent:]: unrecognized selector sent to instance 0x8f2b000
2014-03-19 10:29:48.407 Briefcase[1800:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UITableViewCellContentView pickerView:titleForRow:forComponent:]: unrecognized selector sent to instance 0x8f2b000'
Which i've read is to do with either the datasource, or ARC systems, however none of the responses that I have found relate to or work with the type of set up that I have above. I'm sure it's something really simple but after a few days of failed searching, it's officially driving me crazy.
The problem is most likely that the instance of Picker that is being created in UIPickerViewController is never added to the view hierarchy and thus gets released prematurely (provided we're talking about a project using ARC here).
This leads to the pickerview's delegate and datasource becoming invalid and, basically, pointing at any random object. That's what is causing your crash: A message to your delegate cannot be delivered because the delegate is dead already. The picker still keeps a pointer which used to point at the delegate, but which has become invalid and points at a random object now, in this case a table view cell, which basically doesn't know what to do with this message and crashes.
The problem should go away if you add Picker *picker as an ivar or a retaining / strong property to UIPickerViewController.h - this will retain the picker beyond the scope of the viewDidLoad method and should keep it alive.
But that would be just a workaround, the real problem is your overall design. You said you're new to objective-c and indeed, it looks like you lack a basic understanding of iOS view and view controller hierarchies and, to some degree, the concept of object oriented programming. You might want to dig into something more basic before trying to fix your code because, quite frankly, it should be rather re-written than fixed.
I'd be happy to provide you with suggestions about how to structure your code, but please provide some information about what functionality you'd like to achieve first.
Edit (in response to your comment):
As a rule of thumb, do not spread functionality over several classes unless necessary. For objects, which serve a rather infrastructural purpose, like a specialized textfield or a pickerview, always ask yourself: "If I would like to reuse that object in another project, would that be as easy as using any other existing object, like, for example, UILabel?" If the answer is "No", then something is wrong. Ideally, interface objects are self-contained and to use them, you just invoke them, add them to a view and tell them, which text to display or which options to offer. If that information is subject to change or if the object needs to interact with other parts of your code, make use of delegation and protocols. Under no circumstances should the functionality of your object be tied to hard coded values or rely to some view to have a certain tag.
If you subclass UIView, the resulting object should behave like any other instance of UIView. It should be added to the view hierarchy by you or some object, but it shouldn't add or remove itself. If it works without being added to the view hierarchy at all, something is wrong. A view serves the purpose of being a part in your interface and all the logic it contains should work to that end, not more, not less.
Normally, interface objects should not interfere with one another. If something happens to one object (button pressed, option selected, text changed...) and another object is supposed to reflect that change, it is the view controllers responsibility to make that happen. The view controller is the place where the logic happens. If there is a task which requires a lot of complex logic, it might be a good idea to encapsule that logic into a purpose build class. One such example would be a class which manages network connections. This class should be again self contained: If the view controller needs some remote information, it asks your network class. Once your network class has that information (or failed to retrieve it), it reports back to your view controller. The view controller then updates the interface - under no circumstance should the networking class contain code which affects the interface.
It is important to understand that you could very well ignore these rules and still end up with a working app. And in some cases, the "direct" way may appear to be easier to implement and thus may look very tempting. But you'll pay the price later - once you start debugging your code. If your picker does not behave the way it should, you need to look into several places and wrap your mind around several objects, just to make one interface object behave right. And likely you will break one functionality while fixing the other.
So, try to make it right from the start, even though it requires more planning and learning. Trust me, it pays out, I started out just like you several years ago ;)

ios cellForRowAtIndexPath doesn't get called however numberOfRowsInSection gets called and returns a number

My application is using JASidePanels libraries and I had set them using storyboard. The center view is a UITableView and the left panel is a view in which I call a method (by pressing a button)
- (IBAction)reloadAllFilters:(UIButton *)sender{
MasterViewController *masterController = [self.storyboard instantiateViewControllerWithIdentifier:#"centerViewController"];
NSMutableArray *arrayOfFilterIds = [[NSMutableArray alloc] init];
// another code
masterController.filterIdsToDisplay = arrayOfFilterIds;
[masterController.tableView reloadData];
[self.sidePanelController toggleLeftPanel:self];
}
The thing is, that when the app starts, the number of rows returned by number, but after I call this method, the number of rows is 30 but I cant see nothing.
I think that the problem is that I am instantiating a new masterController and therefor I cant get the actual table view to be displayed? Or am I wrong? Can you please help me?
Yes you are right. You create a new master controller every time you call the method
From UIStoryboard reference:
This method creates a new instance of the specified view controller each time you call it.
You need to get the existing one.
Please set the delegate and datasource to your tableview
like this ...
tableView.delegate = masterController;
tableView.dataSource = masterController;

Programatically set delegate for UICollectionView is not working

I have a viewcontroller A controlling a large view. On that view I have a subview C of type CollectionView.
I want a separate class C_Manager to handle the delegate and dataSource functionality for the C subview
I have the following
in A's viewDidLoad
cManager = [[C_Manager alloc] init];
cManager.collection = C;
self.C.delegate = cManager;
self.C.dataSource = cManager;
in C_Manager.h I have
#interface C_Manager : NSObject <UICollectionViewDataSource,UICollectionViewDelegate>
and in C_Manager.m I have :
// all the functions for the dataSource plus
-(void)collectionView:(UICollectionView*)collectionview didSelectItemAtIndexPath:(NSIndexPath*) indexPath
{
}
I never reach the didSelectItemAtIndexPath. Interestingly, I do reach the functions for the dataSource protocol, and if I disable the line which sets it - I dont reach it anymore...
I checked the view C in the xib - the "User Interraction Enabled" is checked ...
What is wrong ?

ViewController as delegate of custom view's tableview

I have a custom UIView, MyView, with a couple of tableviews in it - tv1 and tv2 - both added programmatically.
I have a custom UIViewController, MyController, which creates an instance of MyView on loadView.
My goal is the following. myView should be the datasource and delegate for myView.tv1, since it doesn't touch my data model and is static.
myController should be the delegate of myView.tv2, since its content will depend on the datasource.
I have added the following to each header:
#interface MyController : UIViewController <UITableViewDelegate, UITableViewDataSource>
#interface MyView : UIView <UITableViewDelegate, UITableViewDataSource>
and added to each the required delegate methods.
In MyView's init, I add that table views, and set the delegate of the first one to self:
tv1 = [[UITableView alloc] initWithFrame:frame1 style:UITableViewStyleGrouped];
tv1.delegate = self;
tv1.datasource = self;
tv2 = [[UITableView alloc] initWithFrame:frame2 style:UITableViewStyleGrouped];
And in my Controller I connect up the second tableview:
- (void)loadView{
self.view = [[MyView alloc] initWithFrame:myFrame];
[(MyView *)self.view tv2].delegate = self;
[(MyView *)self.view tv2].dataSource = self;
}
When I run this, I get a whole mess of runtime errors. Sometimes it complains about a paging control, other times NSCFArray, othertimes no text at all. It always crashes.
I have determined that it is setting the datasource that causes the problem, not the delegate. If I comment out the datasource line in laodView, it runs fine (but with no content of course).
What could cause my to experience a different runtime error each time, and where might I be going wrong?
myView should be the datasource and delegate for myView.tv1, since it
doesn't touch my data model and is static
That's not really MVC, right ?
I think you'll be able to track the problems faster (or easily avoid it) if you prepared separate combined delegate&datasource classes for each table. The table1 datasource might be an internal class of MyView.
It's critically important to keep the delegate/datasource references retained by the table owner as the table will not retain it itself (that might be not so important for the case when you set the delegate/datasource to self both for table1 (MyView) and table2 (MyController), but you need to keep it in mind if you create separate delegate&datasource classes). Anyway you'll need to retain the array you are using as a datasource.

Resources