I have inherited some old iOS code and have attempted to integrate it into a new iOS 6 application. I have implemented most of the code and so far everything has worked. I'm now working on the last bit of that old code. I'm implementing a set of views to show a rss for a news section of my app. I've implemented the categories view, which upon selecting an item would display the individual items within that category. However nothing gets displayed. I've made all the modifications that I'm aware of that I needed to do, however I'm no expert at iOS development and am in need of some guidance. Below is a snapshot of the simulator as it's attempting to display the view, and below that is a copy of my .h and .m files. I don't know what is preventing anything in the table from showing up. And preemptive thanks to any help!
here's the snapshot of the simulator
Here is a snapshot of the storyboard showing the linking to the Table View
Here's the .h file
#import <UIKit/UIKit.h>
#import "BlogRssParser.h"
#class BlogRssParser;
#class BlogRssParserDelegate;
#class BlogRss;
#class XMLCategory;
#interface NewsViewController : UIViewController <UITableViewDataSource,UITableViewDelegate, BlogRssParserDelegate> {
BlogRssParser * _rssParser;
XMLCategory * _currItem;
}
#property (nonatomic, retain) BlogRssParser * rssParser;
#property (readwrite, retain) XMLCategory * currItem;
#property (nonatomic, retain) IBOutlet UITableView *itemTableView;
#end
Here is my .m file
#import "NewsViewController.h"
#import "NewsDetailsViewController.h"
#import "BlogRssParser.h"
#import "BlogRss.h"
#import "XMLCategory.h"
#define kLabelTag 1;
#interface NewsViewController ()
#end
#implementation NewsViewController
#synthesize rssParser = _rssParser;
#synthesize currItem = _currItem;
- (void)navBarInit {
UIBarButtonItem *refreshBarButton = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
target:self action:#selector(reloadRss)];
[self.navigationItem setRightBarButtonItem:refreshBarButton animated:YES];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.itemTableView.delegate = self;
self.itemTableView.dataSource = self;
- (void) viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[self navBarInit];
[self.itemTableView reloadData];
self.itemTableView.userInteractionEnabled = NO;
}
- (void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
_rssParser = [[BlogRssParser alloc]init];
_rssParser.delegate = self;
[[self rssParser]startProcess:[_currItem categoryId]];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)reloadRss{
[[self rssParser]startProcess:[_currItem categoryId]];
[[self itemTableView]reloadData];
}
- (void)processCompleted{
[[self itemTableView]reloadData];
// _tableView.userInteractionEnabled = YES;
[[self itemTableView]setUserInteractionEnabled:YES];
}
-(void)processHasErrors{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"My Title" message:#"Unable to retrieve the news. Please check if you are connected to the internet."
delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [[[self rssParser]rssItems]count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
const CGFloat LABEL_TITLE_HEIGHT = 70.0;
const CGFloat LABEL_WIDTH = 210.0;
NSString * mediaUrl = [[[[self rssParser]rssItems]objectAtIndex:indexPath.row]mediaUrl];
NSData * imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:mediaUrl]];
UIImage * imageFromImageData;
if (imageData == nil) {
imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:#"http://www.urlForImage.image.png"]];
}
imageFromImageData = [[UIImage alloc] initWithData:imageData];
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:#"rssItemCell"];
if(nil == cell){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"rssItemCell"];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
UILabel * _topLabel =
[[UILabel alloc]
initWithFrame:
CGRectMake(
imageFromImageData.size.width + 10.0,
0.0,
LABEL_WIDTH,
LABEL_TITLE_HEIGHT)];
_topLabel.tag = kLabelTag;
_topLabel.opaque = NO;
_topLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin;
_topLabel.backgroundColor = [UIColor clearColor];
_topLabel.textColor = [UIColor colorWithRed:0.25 green:0.0 blue:0.0 alpha:1.0];
_topLabel.highlightedTextColor = [UIColor colorWithRed:1.0 green:1.0 blue:0.9 alpha:1.0];
_topLabel.font = [UIFont systemFontOfSize:[UIFont labelFontSize]];
_topLabel.numberOfLines = 0;
[cell.contentView addSubview:_topLabel];
}
cell.imageView.image = imageFromImageData;
UILabel * topLabel = (UILabel *)[cell.contentView viewWithTag:1];
topLabel.text = [[[[self rssParser]rssItems]objectAtIndex:indexPath.row]title];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NewsDetailsViewController *tlc = [[DetailsViewController alloc]init];
tlc.currentItem = [[[self rssParser]rssItems]objectAtIndex:indexPath.row];
tlc.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController:tlc animated:YES completion:nil];
}
#end
I could not get a conclusion about the problem you are facing.
But here are few things you should check.
Because i cannot see even an empty table view in your screenshot
Do you have the TableView on the Nib file ?
It is mapped from The Nib file to the IBOutlet itemTableView ?
Add at least one table view cell (Drag and drop one prototype cell)..
like this
Then select that cell and give some name in "Reuse Identifier" with this identifier allow datasource..
First thing I would do is make sure that [[[self rssParser] rssItems] count] is actually returning > 0. Also, is this a copy&paste of your .m file? viewDidLoad is missing the closing brace, but Xcode would catch that.
Related
I hope you can help me to set the background color of my navigation bar. As you can see on the first picture below, the bar is light blue/gray, but i want it to be like the second picture "Favoritter".
I have another viewController in my project (see the second picture "Favoritter") where it works. But I can not see what I'm doing wrong here and the navigationBar will only take this light blue/gray color and not yellow.
My code is like this:
------------------InstantCabAppDelegate.m file-----------START-------
//InstantCabAppDelegate.m file
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Create tabBarController instance
tabBarController = [[UITabBarController alloc] initWithNibName:nil bundle:nil];
// Create instances of navigation controller and view controllers
orderController = [[OrderController2 alloc] initWithNibName:#"Order2" bundle:nil];
UINavigationController* firstnavigationController = [[UINavigationController alloc] initWithRootViewController:orderController];
ICStatusViewController *statusController = [[ICStatusViewController alloc] initWithStatus];
UINavigationController *statusNavController = [[UINavigationController alloc] initWithRootViewController:statusController];
ICSettingsViewController *settingsController = [[ICSettingsViewController alloc] init];
UINavigationController *settingsNavController = [[UINavigationController alloc] initWithRootViewController:settingsController];
UIViewController *company_controller = nil;
company_controller = [[ICCompaniesGridController alloc] initWithCompanies:[[NSArray alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"Companies" ofType:#"plist"]]];
tabBarController.viewControllers = [NSArray arrayWithObjects:firstnavigationController, settingsNavController, statusNavController, company_controller, nil];
[window setRootViewController:tabBarController];
[window makeKeyAndVisible];
return YES;
}
------------------ICStatusViewController.m file-----------START-------
// ICStatusViewController.m file
#import "ICStatusViewController.h"
#import "LocalizationSystem.h"
#import "ICTemporaryStore.h"
#import "Debug.h"
#implementation ICStatusViewController
#synthesize doneCallbackBlock=_doneCallbackBlock, cancelCallbackBlock=_cancelCallbackBlock;
#synthesize myTableView, no_statuses, no_statuses_label, delegate;
- (id)initWithStatus
{
if ((self = [super initWithNibName:#"StatusList" bundle:nil]))
{
self.title = AMLocalizedString(#"kStatusTitle", #"");
self.tabBarItem.image = [UIImage imageNamed:#"status_icon"];
self.no_statuses = AMLocalizedString(#"kStatusListNoStatusList", #"");
first_color = TABLE_VIEW_BACKGROUND_COLOR;
second_color = first_color;
self.doneCallbackBlock = nil;
self.cancelCallbackBlock = nil;
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.parentViewController.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"background-nologo"]];
self.view.backgroundColor = [UIColor clearColor];
self.myTableView.backgroundColor = TABLE_VIEW_BACKGROUND_COLOR;
if ([statusObjects count] == 0)
{
self.myTableView.hidden = YES;
self.no_statuses_label.text = self.no_statuses;
self.no_statuses_label.hidden = NO;
no_status_background.hidden = NO;
}
[self.no_statuses_label setTextColor:[UIColor colorWithRed:255.0/255.0 green:255.0/255.0 blue:255.0/255.0 alpha:1.0]];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
if ([statusObjects count] == 0)
{
self.myTableView.hidden = YES;
self.no_statuses_label.text = self.no_statuses;
self.no_statuses_label.hidden = NO;
no_status_background.hidden = NO;
self.navigationItem.rightBarButtonItem = nil;
}
else
{
self.myTableView.hidden = NO;
self.no_statuses_label.hidden = YES;
no_status_background.hidden = YES;
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSInteger retval = 0;
for (int i=0; i<[statusObjects count]; i++)
{
StatusObj *add = [statusObjects getStatusAtIndex:i];
if (add.status_id && [add.status_id length] > 0 && [add.status_type isEqualToString:#"STATUS_ORDER"])
{
retval++;
}
}
return retval;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifierStatus = #"StatusCell";
__unsafe_unretained NSString *CellIdentifier = CellIdentifierStatus;
StatusCell* cell = (StatusCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[StatusCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
[[cell textLabel] setTextColor:TABLE_VIEW_TEXT_LABEL_COLOR];
[[cell detailTextLabel] setTextColor:TABLE_VIEW_DETAIL_TEXT_LABEL_COLOR];
[[cell detailTextLabel] setNumberOfLines:3];
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
dateString = [dateFormat stringFromDate:current_order.order.time];
NSString *str = AMLocalizedString(#"kStatusListDetailsToDay", #"");
textLabelString = [NSString stringWithFormat:#"%# - %#", str, dateString];
[cell.textLabel setText:textLabelString];
[cell.detailTextLabel setText:detailTextString];
[cell setBackgroundColor:[UIColor redColor]];
[cell.dateLabel setBackgroundColor:[UIColor clearColor]];
cell.accessoryType = UITableViewCellAccessoryNone;
return cell;
}
------------------ICStatusViewController.h file-----------START-------
// ICStatusViewController.h
#import <UIKit/UIKit.h>
#import "Status.h"
#import "StatusCell.h"
#import "StatusControllerDelegate.h"
#import "ICStatusDetailsController.h"
typedef void (^ICStatusViewControllerDoneCallbackBlock)(id userInfo);
typedef void (^ICStatusViewControllerCancelCallbackBlock)(void);
#interface ICStatusViewController : UIViewController <UITableViewDelegate, UITableViewDataSource, UIActionSheetDelegate, ICStatusDetailsControllerDelegate> {
id<Statuses> statusObjects;
NSString *no_statuses;
NSOperationQueue *queue;
NSTimer *statusTimer;
__unsafe_unretained id<StatusControllerDelegate> delegate;
UIColor *first_color;
UIColor *second_color;
IBOutlet __unsafe_unretained UITableView *myTableView;
IBOutlet __unsafe_unretained UILabel *no_statuses_label;
IBOutlet __unsafe_unretained UIImageView *no_status_background;
#private
ICStatusViewControllerDoneCallbackBlock _doneCallbackBlock;
ICStatusViewControllerCancelCallbackBlock _cancelCallbackBlock;
}
#property (nonatomic, unsafe_unretained) UITableView* myTableView;
#property (nonatomic, copy) NSString* no_statuses;
#property (nonatomic, unsafe_unretained) UILabel* no_statuses_label;
#property (nonatomic, unsafe_unretained) id <StatusControllerDelegate> delegate;
#property (nonatomic, copy) ICStatusViewControllerDoneCallbackBlock doneCallbackBlock;
#property (nonatomic, copy) ICStatusViewControllerCancelCallbackBlock cancelCallbackBlock;
- (id)initWithStatus;
#end
You can either set the tint color of the navigation bar OR use a IMAGE instead of navigation bar and hide the navigation bar, using:
navigationController.navigationBarHidden = YES;
You are not talking about a UITableView, but about the UINavigationBar on the top. I fixed your question to reflect that. Basically there are two ways to set its tintColor:
The easier option would be to use the appearance protocol (iOS 5 and later), as this will change every NavigationBar in the whole app:
[[UINavigationBar appearance] setTintColor:[UIColor yellowColor]];
Or you do it on every single UINavigationBar of every UINavigationController.
[navigationController.navigationBar setTintColor:[UIColor yellowColor]];
just add this line for set yellow color to navigationcontroller in viewDidLoad: method of ICStatusViewController class..
[self.navigationController.navigationBar setTintColor:[UIColor yellowColor]];
and also with image like bellow..
[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:#"yourImageName"] forBarMetrics:UIBarMetricsDefault];// write your image name like yellow image
i hope this help you...
What's your tableView's style? If tableView's style is UITableViewStyleGrouped, you can't change backgroundColor on iOS 6. Try to change tableView's backgroundView.
self.settingsTableView = [[UITableView alloc] initWithFrame:rect
style:UITableViewStyleGrouped];
UIView *view = [[UIView alloc] initWithFrame:settingsTableView.frame];
view.backgroundColor = [UIColor redColor];
settingsTableView.backgroundView = view;
Sounds like a question that has been answered... maybe but i have checked all of the possible solutions i believe and nothing will work for me.
My .h file looks like this
#import <UIKit/UIKit.h>
#interface epsMenuPage : UIViewController<UITableViewDelegate,UITableViewDataSource>{
NSArray *listData;
...
UITableView *menuList;
...
}
#property (nonatomic,retain) NSArray *listData;
...
#property (nonatomic, retain) IBOutlet UITableView *menuList;
...
#end
My .m file looks like this
#implementation epsMenuPage
#synthesize listData;
...
#synthesize menuList;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
//Arrays credit,debit and both
creditListData = [[NSArray alloc]initWithObjects:#"Return",#"Force Sale",#"Authorize Only",#"Total Sales",#"Items Sold",#"Reciept's", nil];
debitListData = [[NSArray alloc]initWithObjects:#"Return",#"Force Sale",#"Authorize Only",#"Total Sales",#"Items Sold",#"Reciept's", nil];
bothListData = [[NSArray alloc]initWithObjects:#"Batch History",#"Settle Batch", nil];
self.listData = creditListData;
[menuList reloadData];
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
self.view.backgroundColor =[UIColor colorWithRed:255/255.0 green:95/255.0 blue:95/255.0 alpha:1.0];
[colorChange setBackgroundColor:[UIColor colorWithRed:255/255.0 green:95/255.0 blue:95/255.0 alpha:1.0]];
[self.view addSubview:creditTabButton];
[self.view addSubview:debitTabButton];
[self.view addSubview:bothTabButton];
[self.view addSubview:creditButtonText];
[self.view addSubview:debitButtonText];
[self.view addSubview:bothBottonText];
[self.view addSubview:colorChange];
}
- (void)viewDidUnload
{
[self setTitleBAckButton:nil];
[self setTitleSettingsButton:nil];
[self setCreditTabButton:nil];
[self setDebitTabButton:nil];
[self setBothTabButton:nil];
[self setMenuList:nil];
[self setColorChange:nil];
[self setCreditButtonText:nil];
[self setDebitButtonText:nil];
[self setBothBottonText:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.listData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *SimpleTableIdentifier = #"tableID";
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:SimpleTableIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:SimpleTableIdentifier] autorelease];
}
NSUInteger row = [indexPath row];
cell.textLabel.text = [self.listData objectAtIndex:row];
return cell;
}
- (void)dealloc {
[titleBAckButton release];
[titleSettingsButton release];
[creditTabButton release];
[debitTabButton release];
[bothTabButton release];
[menuList release];
[colorChange release];
[creditButtonText release];
[debitButtonText release];
[bothBottonText release];
[listData release];
[super dealloc];
}
- (IBAction)titleBackClick:(id)sender {
[self.parentViewController dismissModalViewControllerAnimated:YES];
}
- (IBAction)titleSettingsClick:(id)sender {
}
- (IBAction)creditTabClick:(id)sender {
self.listData = creditListData;
[menuList reloadData];
[colorChange setBackgroundColor:[UIColor colorWithRed:255/255.0 green:95/255.0 blue:95/255.0 alpha:1.0]];
[self.view addSubview:creditTabButton];
[self.view addSubview:creditButtonText];
[self.view addSubview:colorChange];
self.view.backgroundColor = [UIColor colorWithRed:255/255.0 green:95/255.0 blue:95/255.0 alpha:1.0];
}
- (IBAction)debitTabClick:(id)sender {
self.listData = debitListData;
[menuList reloadData];
[colorChange setBackgroundColor:[UIColor colorWithRed:244/255.0 green:133/255.0 blue:33/255.0 alpha:1.0]];
[self.view addSubview:debitTabButton];
[self.view addSubview:debitButtonText];
[self.view addSubview:colorChange];
self.view.backgroundColor = [UIColor colorWithRed:244/255.0 green:133/255.0 blue:33/255.0 alpha:1.0];
}
- (IBAction)bothTabClick:(id)sender {
self.listData = bothListData;
[menuList reloadData];
[colorChange setBackgroundColor:[UIColor colorWithRed:72/255.0 green:72/255.0 blue:255/255.0 alpha:1.0]];
[self.view addSubview:bothTabButton];
[self.view addSubview:bothBottonText];
[self.view addSubview:colorChange];
self.view.backgroundColor = [UIColor colorWithRed:72/255.0 green:72/255.0 blue:255/255.0 alpha:1.0];
}
#end
I really for the life of me can not figure out why it wont display to my TableView, i have tried so many different tutorials.
any help is greatly appreciated.
You're never adding the menuList table view to your view. Add it and see if that does the trick:
// In -viewDidLoad
[self.view addSubview:menuList];
EDIT 1: Did you declare properties in your .h? These aren't visible, so it appears as if you're not creating or adding your table view to the view controller's view. However, if you are using IBOutlets, then this probably isn't the issue.
EDIT 2: From the comments below, your dataSource is nil, which is exactly why nothing is being displayed. Make sure your table view in Interface Builder has its dataSource outlet pointing to your view controller. To be double sure, delete the table view from Interface Builder and add it back again. Make sure your connections are exactly right. Also try cleaning the project and rebuilding, as well as restarting Xcode.
It looks like you are missing the required datasource method:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView; {
return 1;
}
Also, it looks like you are not actually initializing your UIButton's, or anything you are adding as a subview. Are you using a nib?
i have a problem with my app crashing when my custom TableViewCell gets released.
the Cell gets initialized like the following in cellForRowAtIndexPath:
SearchTableViewCell *cell = (SearchTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[SearchTableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
cell.nameLabel.text = #"some text";
cell.addressLabel.text = #"some more text";
the cell class itself looks like this
#import <UIKit/UIKit.h>
#class EGOImageView;
#interface SearchTableViewCell : UITableViewCell {
UILabel *nameLabel;
UILabel *addressLabel;
EGOImageView *imageView;
}
#property (nonatomic, retain) UILabel *nameLabel;
#property (nonatomic, retain) UILabel *addressLabel;
- (UILabel *)labelWithColor:(UIColor*)color selectedColor:(UIColor*)selectedColor fontSize:(CGFloat)fontSize bold:(BOOL)bold frame:(CGRect)rect;
- (void)setThumb:(NSString*)thumb;
#end
.m
#import "SearchTableViewCell.h"
#import "EGOImageView.h"
#import "UIView+Additions.h"
#implementation SearchTableViewCell
#synthesize nameLabel = _nameLabel, addressLabel = _addressLabel;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) {
// Initialization code
UIView *myContentView = self.contentView;
// Name
_nameLabel = [self labelWithColor:[UIColor blackColor] selectedColor:[UIColor whiteColor] fontSize:16.0f bold:YES frame:CGRectMake(140.0f, 16.0f, 181.0f, 21.0f)];
[myContentView addSubview:_nameLabel];
[_nameLabel release];
// Adress
_addressLabel = [self labelWithColor:[UIColor blackColor] selectedColor:[UIColor whiteColor] fontSize:13.0f bold:YES frame:CGRectMake(140.0f, _nameLabel.bottom, 181.0f, 21.0f)];
[myContentView addSubview:_addressLabel];
[_addressLabel release];
// Image
imageView = [[EGOImageView alloc] initWithPlaceholderImage:[UIImage imageNamed:#"placeholder.png"]];
imageView.frame = CGRectMake(9.0f, 9.0f, 120.0f, 80.0f);
[myContentView addSubview:imageView];
[imageView release];
}
return self;
}
- (UILabel *)labelWithColor:(UIColor*)color selectedColor:(UIColor*)selectedColor fontSize:(CGFloat)fontSize bold:(BOOL)bold frame:(CGRect)rect {
UIFont *font;
if(bold) {
font = [UIFont boldSystemFontOfSize:fontSize];
} else {
font = [UIFont systemFontOfSize:fontSize];
}
UILabel *label = [[UILabel alloc] initWithFrame:rect];
label.backgroundColor = [UIColor clearColor];
label.textColor = color;
label.highlightedTextColor = selectedColor;
label.font = font;
return label;
}
- (void)setThumb:(NSString*)thumb {
imageView.imageURL = [NSURL URLWithString:thumb];
}
- (void)willMoveToSuperview:(UIView *)newSuperview {
[super willMoveToSuperview:newSuperview];
if(!newSuperview) {
[imageView cancelImageLoad];
}
}
- (void)dealloc {
[_addressLabel release];
[_nameLabel release];
[imageView release];
[super dealloc];
}
#end
does anybody have an idea why my app crashes on releasing such a cell? commenting out the 2 labels and the image view on dealloc method, the app doesn't crash, but then there will be a memory leak right?
thanks for all hints! please leave a comment if something is unclear!
imageView is being released twice, once when it is created:
imageView = [[EGOImageView alloc] initWithPlaceholderImage:[UIImage imageNamed:#"placeholder.png"]];
imageView.frame = CGRectMake(9.0f, 9.0f, 120.0f, 80.0f);
[myContentView addSubview:imageView];
[imageView release];
and once in dealloc:
- (void)dealloc {
[_addressLabel release];
[_nameLabel release];
[imageView release];
[super dealloc];
}
You already release the memory for that labels after adding to view,again you are trying to release memory those objects are already relese in dealloc method that's why it is killing.if you remove 3 statements in dealloc method it will not crash.
I think the Problem is that you release your properties direct in the initWithStyle function and additional to that in dealloc again. Try removing the release from initWithStyle:
Furthermore you named your variables without _ in the interface but with _ #synthesize'ing in the implementation
The iOS app I'm currently working on is tabbar-based, and one of the tab is a UITableViewController.
The thing is, when I open this tab with an empty datasource (for whatever reason), I'd like to bring another view, with some kind of message/image, instead of the blank view I get with the tableviewcontroller.
I tried something like that :
- (void)viewWillAppear:(BOOL)animated {
if ([myData count] == 0) {
if (!emptyView) {
emptyView = [[UIView alloc] initWithFrame:self.view.frame];
UILabel *emptyMsg = [[UILabel alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height / 2, self.view.frame.size.width, 20)];
emptyMsg.text = #"This is Empty !";
emptyMsg.textAlignment = UITextAlignmentCenter;
[emptyView addSubview:emptyMsg];
}
[self.view insertSubview:emptyView atIndex:0];
}
else {
if (emptyView != nil) { [emptyView removeFromSuperview]; emptyView = nil; }
[self.tableView reloadData];
[super viewWillAppear:animated];
}
}
With emptyView defined as an iVar in the view controller.
But It doesn't work as expected, and I can't find the reason :/
Could any of you give it a look and give me the proper way to do this kind of behavior ?
Thanks,
I solved this problem by adding a UIView in the tableview header with a frame size equal to tableview size and disallowing user interaction on the tableview:
UIView *emptyView = [[UIView alloc] initWithFrame:self.tableView.frame];
/* Customize your view here or load it from a NIB */
self.tableView.tableHeaderView = emptyView;
self.tableView.userInteractionEnabled = NO;
When you have data you just remove the header and reenable user interaction:
self.tableView.tableHeaderView = nil;
self.tableView.userInteractionEnabled = YES;
UITableViewController doesn't allow you to add subviews to it's view (the tableView).
You should make a UIViewController and add the UITableView yourself with your optional emptyView.
Don't forget to set the dataSource and the delegate!
Update : I've made a subclass of UIViewController to avoid mimics UITableViewController every time.
.h
//
// GCTableViewController.h
// GCLibrary
//
// Created by Guillaume Campagna on 10-06-17.
// Copyright 2010 LittleKiwi. All rights reserved.
//
#import <UIKit/UIKit.h>
//Subclass of UIViewController that mimicks the UITableViewController except that the tableView is a subview of self.view and allow change of the frame of the tableView
#interface GCTableViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
#property (nonatomic, readonly) UITableView *tableView;
- (id) initWithStyle:(UITableViewStyle)style;
//Subclass if you want to change the type of tableView. The tableView will be automatically placed later
- (UITableView*) tableViewWithStyle:(UITableViewStyle) style;
#end
.m
//
// GCTableViewController.m
// GCLibrary
//
// Created by Guillaume Campagna on 10-06-17.
// Copyright 2010 LittleKiwi. All rights reserved.
//
#import "GCTableViewController.h"
#implementation GCTableViewController
#synthesize tableView;
- (id) initWithStyle:(UITableViewStyle) style {
if (self = [super initWithNibName:nil bundle:nil]) {
tableView = [[self tableViewWithStyle:style] retain];
self.tableView.delegate = self;
self.tableView.dataSource = self;
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
[self.view addSubview:self.tableView];
self.tableView.frame = self.view.bounds;
self.tableView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
}
- (void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
}
#pragma mark TableView methods
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger) tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {
return 0;
}
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
return nil;
}
#pragma mark Getter
- (UITableView *) tableViewWithStyle:(UITableViewStyle)style {
return [[[UITableView alloc] initWithFrame:CGRectZero style:style] autorelease];
}
- (void)dealloc {
[tableView release];
tableView = nil;
[super dealloc];
}
#end
You could perhaps try setting the number of rows to zero. Then inserting the no results view as the header view.
I'm completely new to iPhone development. I have a query regarding how to implement scroll view in table view. I'm using following code
#import <UIKit/UIKit.h>
#class ScrollViewViewController;
#interface ScrollViewAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
ScrollViewViewController *viewController;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) IBOutlet ScrollViewViewController *viewController;
#end
////////////////////////////////////////////
#import "ScrollViewAppDelegate.h"
#import "ScrollViewViewController.h"
#implementation ScrollViewAppDelegate
#synthesize window;
#synthesize viewController;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Override point for customization after app launch
[window addSubview:viewController.view];
[window makeKeyAndVisible];
}
- (void)dealloc {
[viewController release];
[window release];
[super dealloc];
}
#end
///////////////////////////
#import <UIKit/UIKit.h>
#interface MyTableCell : UITableViewCell {
NSMutableArray *columns;
}
- (void)addColumn:(CGFloat)position;
#end
//////////////////////////
#import "MyTableCell.h"
#implementation MyTableCell
- (id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
if (self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) {
// Initialization code
columns = [NSMutableArray arrayWithCapacity:5];
[columns retain];
}
return self;
}
- (void)addColumn:(CGFloat)position {
[columns addObject:[NSNumber numberWithFloat:position]];
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void)drawRect:(CGRect)rect {
CGContextRef ctx = UIGraphicsGetCurrentContext();
// just match the color and size of the horizontal line
CGContextSetRGBStrokeColor(ctx, 0.5, 0.5, 0.5, 1.0);
CGContextSetLineWidth(ctx, 0.25);
for (int i = 0; i < [columns count]; i++) {
// get the position for the vertical line
CGFloat f = [((NSNumber*) [columns objectAtIndex:i]) floatValue];
CGContextMoveToPoint(ctx, f, 0);
CGContextAddLineToPoint(ctx, f, self.bounds.size.height);
}
CGContextStrokePath(ctx);
[super drawRect:rect];
}
- (void)dealloc {
[super dealloc];
[columns dealloc];
}
#end
//////////////////////
#import <UIKit/UIKit.h>
#interface RootViewController : UITableViewController {
}
#end
/////////////////
#import "RootViewController.h"
#import "MyTableCell.h"
#implementation RootViewController
#define LABEL_TAG 1
#define VALUE_TAG 2
#define FIRST_CELL_IDENTIFIER #"TrailItemCell"
#define SECOND_CELL_IDENTIFIER #"RegularCell"
- (void)viewDidLoad {
// Add the following line if you want the list to be editable
// self.navigationItem.leftBarButtonItem = self.editButtonItem;
self.title = #"Grids!";
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
return 19;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *MyIdentifier = [NSString stringWithFormat:#"MyIdentifier %i", indexPath.row];
MyTableCell *cell = (MyTableCell *)[tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[[MyTableCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(0.0, 0, 30.0,
tableView.rowHeight)] autorelease];
[cell addColumn:40];
label.tag = LABEL_TAG;
label.font = [UIFont systemFontOfSize:12.0];
label.text =#"S.NO";// [NSString stringWithFormat:#"%d", indexPath.row];
label.textAlignment = UITextAlignmentRight;
label.textColor = [UIColor redColor];
label.autoresizingMask = UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:label];
label = [[[UILabel alloc] initWithFrame:CGRectMake(40.0, 0, 70.0,
tableView.rowHeight)] autorelease];
[cell addColumn:120];
label.tag = VALUE_TAG;
label.font = [UIFont systemFontOfSize:12.0];
// add some silly value
label.text =#"Product ID";// [NSString stringWithFormat:#"%d", indexPath.row * 4];
label.textAlignment = UITextAlignmentRight;
label.textColor = [UIColor blueColor];
label.autoresizingMask = UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:label];
label = [[[UILabel alloc] initWithFrame:CGRectMake(134.0, 0, 70.0,
tableView.rowHeight)] autorelease];
[cell addColumn:220];
label.tag = VALUE_TAG;
label.font = [UIFont systemFontOfSize:12.0];
// add some silly value
label.text =#"Product Name";// [NSString stringWithFormat:#"%d", indexPath.row * 4];
label.textAlignment = UITextAlignmentRight;
label.textColor = [UIColor greenColor];
label.autoresizingMask = UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:label];
label = [[[UILabel alloc] initWithFrame:CGRectMake(230.0, 0, 70.0,
tableView.rowHeight)] autorelease];
[cell addColumn:310];
label.tag = VALUE_TAG;
label.font = [UIFont systemFontOfSize:12.0];
// add some silly value
label.text =#"Customer Name";// [NSString stringWithFormat:#"%d", indexPath.row * 4];
label.textAlignment = UITextAlignmentRight;
label.textColor = [UIColor greenColor];
label.autoresizingMask = UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:label];
label = [[[UILabel alloc] initWithFrame:CGRectMake(320.0, 0, 70.0,
tableView.rowHeight)] autorelease];
[cell addColumn:400];
label.tag = VALUE_TAG;
label.font = [UIFont systemFontOfSize:12.0];
// add some silly value
label.text =#"Customer Product";// [NSString stringWithFormat:#"%d", indexPath.row * 4];
label.textAlignment = UITextAlignmentRight;
label.textColor = [UIColor greenColor];
label.autoresizingMask = UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:label];
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated {
}
- (void)viewDidDisappear:(BOOL)animated {
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
// Release anything that's not essential, such as cached data
}
- (void)dealloc {
[super dealloc];
}
#end
////////////
#import <UIKit/UIKit.h>
#interface ScrollViewViewController : UIViewController<UIScrollViewDelegate> {
}
#end
/////////////
#import "ScrollViewViewController.h"
#import "RootViewController.h"
#implementation ScrollViewViewController
/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
// Custom initialization
}
return self;
}
*/
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
RootViewController *RootViewControllerLink = [[RootViewController alloc]initWithNibName:#"RootViewController" bundle:nil];
RootViewControllerLink.view.tag = 100;
/* UIImageView *imgView = [[[UIImageView alloc] initWithImage:
[UIImage imageNamed:#"winkler-gnu-blue.png"]] autorelease];
imgView.tag = 100;
*/
UIScrollView *scrollView = [[[UIScrollView alloc]
initWithFrame:CGRectMake(0,0,320,480)] autorelease];
scrollView.delegate = self;
scrollView.minimumZoomScale = 0.25;
scrollView.maximumZoomScale = 2;
scrollView.bounces = NO;
scrollView.showsHorizontalScrollIndicator = NO;
scrollView.showsVerticalScrollIndicator = NO;
scrollView.contentSize = RootViewControllerLink.view.frame.size;
scrollView.contentOffset =
CGPointMake((RootViewControllerLink.view.frame.size.width-320)/2,
(RootViewControllerLink.view.frame.size.height-480)/2);
[scrollView addSubview:RootViewControllerLink.view];
self.view = scrollView;
}
/*- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
return [self.view viewWithTag:100];
}
- (BOOL)touchesShouldBegin:(NSSet *)touches withEvent:(UIEvent *)event inContentView:(UIView *)view
{
return YES;
}// default returns YES
- (BOOL)touchesShouldCancelInContentView:(UIView *)view
{
return YES;
}
*/
// not called if canCancelContentTouches is NO. default returns YES if view isn't UIControl
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
#end
In above code if I set scroll for UIIMage then it works but if I set scroll view for RootViewController then it doesn't work.
I didn't read your code, please reformat it so others can read it easily.
What do you mean by a UIScrollView in an UITableView? Inside the cells? Still I don't get it.
FYI UITableView inherits from UIScrollView ...
What functionality do you exactly want to achieve?
I will recommend to read some of the samples given by Apple. There are very good and extensive examples specially regarding UIKit.