Please bear with me, I am just starting iOS development. I am trying to display a custom tableViewCell within a storyboard tableView. I have done the following.
I have created a new .xib with a tableViewCell in it
I have then created a custom class for this. the .h file looks like this
#import <UIKit/UIKit.h>
#interface CustomTableCell : UITableViewCell
#property (weak, nonatomic) IBOutlet UIImageView *thumbnailImageView;
#property (weak, nonatomic) IBOutlet UILabel› *titleLabel;
#end
Then in my TableViewController.m I have imported the CustomTableCell.h and I am doing following for 10 rows
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 10;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"CustomTableCell";
CustomTableCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"CustomTableCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.titleLabel.text ="test text";
return cell;
}
This seems fine to build, but when the project loads nothing happens. Any advice will be great.
I have placed a breakpoint in the cellForRowAtIndexPath method, however it never reaches this point. here is a screen shot of the simulator
You must register your .xib file. In your viewDidLoad method, add the following:
[self.tableView registerNib:[UINib nibWithNibName:#"CustomTableCell" bundle:nil]
forCellReuseIdentifier:#"CustomTableCell"];
The way you are loading the nib is really old-fashioned and outdated. It is much better (since iOS 6) to register the nib and use dequeueReusableCellWithIdentifier:forIndexPath:.
See my explanation of all four ways of getting a custom cell.
Ensure that the delegate and datasource are set in the storyboard for the UITableView. This will ensure that cellForRowAtIndexPath is getting called for each row. You can put an NSLog message in that method to verify the same thing.
Also, since you are using a storyboard, you may want to look into Prototype Cells for the UITableView. They are a much easier way of doing the same thing - creating a UITableView with custom cells.
Here's a decent tutorial on using Prototype cells within your storyboard's UITableView:
http://www.raywenderlich.com/5138/beginning-storyboards-in-ios-5-part-1
- (void) viewDidLoad {
[super viewDidLoad];
UINib *cellNib = [UINib nibWithNibName:#"CustomTableCell" bundle:[NSBundle mainBundle]];
[self.tableView registerNib:cellNib forCellReuseIdentifier:#"CustomTableCell"];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"CustomTableCell";
CustomTableCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
cell = [[CustomTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.titleLabel.text ="test text";
return cell;
}
A very basic question, but have you implemented the tableview delegate method that indicates how many cells should be displayed? The delegate method is the following:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//Return number of cells to display here
return 1;
}
Be sure to have only one item in your xib (Uitableviewcell instance)
#import <UIKit/UIKit.h>
#import "DetailViewController.h"
#import "NewViewController.h"
#import "CustomCellVC.h"
#interface FirstVC : UIViewController
{
DetailViewController *detailViewController;
NewViewController *objNewViewController;
CustomCellVC *objCustom;
NSMutableData *webData;
NSArray *resultArray;
//IBOutlet UIButton *objButton;
}
#property(strong,nonatomic)IBOutlet DetailViewController *detailViewController;
#property(strong,nonatomic)IBOutlet UITableView *objTable;
-(void)loginWS;
-(IBAction)NewFeatureButtonClk:(id)sender;
#end
#import "FirstVC.h"
#interface FirstVC ()
#end
#implementation FirstVC
#synthesize objTable;
#synthesize detailViewController;
- (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 from its nib.
objTable.frame = CGRectMake(0, 20, 320, 548);
[self loginWS];
}
-(void)loginWS
{
//Para username password
NSURL *url = [NSURL URLWithString:#"http://192.168.0.100/FeatureRequestComponent/FeatureRequestComponentAPI"];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
[req setHTTPMethod:#"POST"];
[req addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
// [req addValue:[NSString stringWithFormat:#"%i",postBody.length] forHTTPHeaderField:#"Content-Length"];
[req setTimeoutInterval:60.0 ];
//[req setHTTPBody:postBody];
//[cell setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:#"CellBg.png"]]];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:req delegate:self];
if (connection)
{
webData = [[NSMutableData alloc]init];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
resultArray = [[NSArray alloc]initWithArray:[responseDict valueForKey:#"city"]];
NSLog(#"resultArray: %#",resultArray);
[self.objTable reloadData];
}
-(IBAction)NewFeatureButtonClk:(id)sender
{
objNewViewController=[[NewViewController alloc]initWithNibName:#"NewViewController" bundle:nil];
// Push the view controller.
[self.navigationController pushViewController:objNewViewController animated:YES];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//#warning Potentially incomplete method implementation.
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//#warning Incomplete method implementation.
// Return the number of rows in the section.
return [resultArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
objCustom = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (objCustom == nil) {
objCustom = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
//objCustom.persnName.text=[[resultArray objectAtIndex:indexPath.row]valueForKey:#"Name"];
//objCustom.persnAge.text=[[resultArray objectAtIndex:indexPath.row]valueForKey:#"Age"];
// Configure the cell...
objCustom.textLabel.text = [[resultArray objectAtIndex:indexPath.row] valueForKey:#"FeatureTitle"];
objCustom.detailTextLabel.text = [[resultArray objectAtIndex:indexPath.row] valueForKey:#"Description"];
return objCustom;
}
#pragma mark - Table view delegate
// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here, for example:
// Create the next view controller.
detailViewController = [[DetailViewController alloc]initWithNibName:#"DetailViewController" bundle:nil];
detailViewController.objData=[resultArray objectAtIndex:indexPath.row];
// Pass the selected object to the new view controller.
// Push the view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
#import <UIKit/UIKit.h>
#import "DetailData.h"
#interface DetailViewController : UIViewController
{
DetailData *objData;
}
#property(strong,nonatomic)IBOutlet UITextField *usecaseTF;
#property(strong,nonatomic)IBOutlet UITextView *featureTF;
#property(strong,nonatomic)IBOutlet UILabel *priority;
#property(strong,nonatomic)IBOutlet UIButton *voteBtn;
#property(strong,nonatomic)IBOutlet DetailData *objData;
-(IBAction)voteBtnClk:(id)sender;
#end
#import "DetailViewController.h"
#interface DetailViewController ()
#end
#implementation DetailViewController
#synthesize objData,usecaseTF,featureTF,priority,voteBtn;
- (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 from its nib.
}
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
usecaseTF.text=objData.usecaseTF;
featureTF.text=objData.featureTF;
priority.text=objData.priority;
}
-(IBAction)voteBtnClk:(id)sender
{
if ([voteBtn.currentImage isEqual:#"BtnGreen.png"])
{
[voteBtn setImage:[UIImage imageNamed:#"BtnBlack.png"] forState:UIControlStateNormal];
}
else
{
[voteBtn setImage:[UIImage imageNamed:#"BtnGreen.png"] forState:UIControlStateNormal];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
#import <UIKit/UIKit.h>
#interface NewViewController : UIViewController<UITextFieldDelegate>
{
UITextField *currentTF;
}
#property(strong,nonatomic) IBOutlet UITextField *nameTF;
#property(strong,nonatomic)IBOutlet UITextField *emailTF;
#property(strong,nonatomic)IBOutlet UITextField *featureTF;
#property(strong,nonatomic)IBOutlet UITextField *descpTF;
#property(strong,nonatomic)IBOutlet UITextView *UsecaseTV;
#property(strong,nonatomic)IBOutlet UIButton *HighBtn;
#property(strong,nonatomic)IBOutlet UIButton *LowBtn;
#property(strong,nonatomic)IBOutlet UIButton *MediumBtn;
-(IBAction)sendRequestBtnClk:(id)sender;
-(IBAction)RadioBtnHigh:(id)sender;
-(IBAction)RadioBtnLow:(id)sender;
-(IBAction)RadioBtnMedium:(id)sender;
-(void)radioBtnClick;
#end
#import "NewViewController.h"
#interface NewViewController ()
#end
#implementation NewViewController
#synthesize nameTF,emailTF,featureTF,descpTF,UsecaseTV,LowBtn,HighBtn,MediumBtn;
- (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 from its nib.
self.title=#"Did I Know This";
currentTF=[[UITextField alloc]init];
[ self radioBtnClick];
}
-(IBAction)sendRequestBtnClk:(id)sender
{
if (nameTF.text.length==0)
{
[self showAlertMessage:#"Please enter Your Name"];
// return NO;
}
else if (emailTF.text.length==0)
{
[self showAlertMessage:#"Please enter email ID"];
}
if (emailTF.text.length==0)
{
[self showAlertMessage:#"Please enter email address"];
}
else if ([self emailValidation:emailTF.text]==NO)
{
[self showAlertMessage:#"Please enter valid email address"];
}
else if(featureTF.text.length==0)
{
[self showAlertMessage:#"Please Confirm the Feature title"];
}
}
-(BOOL) emailValidation:(NSString *)emailTxt
{
NSString *emailRegex = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegex];
return [emailTest evaluateWithObject:emailTxt];
}
-(void)showAlertMessage:(NSString *)msg
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Note" message:msg delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
}
#pragma mark TextField Delegates
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[currentTF resignFirstResponder];
return YES;
}
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
currentTF = textField;
[self animateTextField:textField up:YES];
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
currentTF = textField;
[self animateTextField:textField up:NO];
}
-(void)animateTextField:(UITextField*)textField up:(BOOL)up
{
int movementDistance = 0; // tweak as needed
if (textField.tag==103||textField.tag==104||textField.tag==105||textField.tag==106)
{
movementDistance = -130;
}
else if (textField.tag==107||textField.tag==108)
{
movementDistance = -230;
}
else
{
movementDistance = 00;
}
const float movementDuration = 0.3f; // tweak as needed
int movement = (up ? movementDistance : -movementDistance);
[UIView beginAnimations: #"animateTextField" context: nil];
[UIView setAnimationBeginsFromCurrentState: YES];
[UIView setAnimationDuration: movementDuration];
self.view.frame = CGRectOffset(self.view.frame, 0, movement);
[UIView commitAnimations];
}
-(void)radioBtnClick
{
if ([HighBtn.currentImage isEqual:#"radiobutton-checked.png"])
{
[LowBtn setImage:[UIImage imageNamed:#"radiobutton-checked.png"] forState:UIControlStateNormal];
[MediumBtn setImage:[UIImage imageNamed:#"radiobutton-unchecked.png"] forState:UIControlStateNormal];
[HighBtn setImage:[UIImage imageNamed:#"radiobutton-unchecked.png"] forState:UIControlStateNormal];
}
else
{
[LowBtn setImage:[UIImage imageNamed:#"radiobutton-unchecked.png"] forState:UIControlStateNormal];
[HighBtn setImage:[UIImage imageNamed:#"radiobutton-checked.png"] forState:UIControlStateNormal];
[MediumBtn setImage:[UIImage imageNamed:#"radiobutton-unchecked.png"] forState:UIControlStateNormal];
}
}
-(IBAction)RadioBtnHigh:(id)sender
{
[LowBtn setImage:[UIImage imageNamed:#"radiobutton-checked.png"] forState:UIControlStateNormal];
[HighBtn setImage:[UIImage imageNamed:#"radiobutton-unchecked.png"] forState:UIControlStateNormal];
[MediumBtn setImage:[UIImage imageNamed:#"radiobutton-unchecked.png"] forState:UIControlStateNormal];
}
-(IBAction)RadioBtnLow:(id)sender
{
[LowBtn setImage:[UIImage imageNamed:#"radiobutton-unchecked.png"] forState:UIControlStateNormal];
[HighBtn setImage:[UIImage imageNamed:#"radiobutton-checked.png"] forState:UIControlStateNormal];
[MediumBtn setImage:[UIImage imageNamed:#"radiobutton-unchecked.png"] forState:UIControlStateNormal];
}
-(IBAction)RadioBtnMedium:(id)sender
{
[LowBtn setImage:[UIImage imageNamed:#"radiobutton-unchecked.png"] forState:UIControlStateNormal];
[HighBtn setImage:[UIImage imageNamed:#"radiobutton-unchecked.png"] forState:UIControlStateNormal];
[MediumBtn setImage:[UIImage imageNamed:#"radiobutton-checked.png"] forState:UIControlStateNormal];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
#import <UIKit/UIKit.h>
#interface CustomCellVC : UITableViewCell
#property (strong,nonatomic) IBOutlet UIImageView *persnImage;
#property (strong,nonatomic) IBOutlet UIButton *thumbImage;
#property (strong,nonatomic) IBOutlet UIImageView *calenderImage;
#property (strong,nonatomic) IBOutlet UIButton *voteImage;
#property (strong,nonatomic) IBOutlet UIButton *selectImage;
#property (strong,nonatomic) IBOutlet UILabel *publabel;
#property (strong,nonatomic) IBOutlet UILabel *IdLabel;
#property (strong,nonatomic) IBOutlet UILabel *decpLabel;
#property (strong,nonatomic) IBOutlet UITextField *ansTF;
#end
#import "CustomCellVC.h"
#implementation CustomCellVC
#synthesize ansTF,persnImage,publabel,thumbImage,calenderImage,voteImage,selectImage,IdLabel,decpLabel;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
#end
#synthesize ObjFirstVC,objNavc;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
ObjFirstVC=[[FirstVC alloc ]initWithNibName:#"FirstVC" bundle:nil];
objNavc=[[UINavigationController alloc]initWithRootViewController:ObjFirstVC];
[self.window addSubview:objNavc.view];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
#import <Foundation/Foundation.h>
#interface DetailData : NSObject
#property(strong,nonatomic)IBOutlet UITextField *usecaseTF;
#property(strong,nonatomic)IBOutlet UITextView *featureTF;
#property(strong,nonatomic)IBOutlet UILabel *priority;
#property(strong,nonatomic)IBOutlet UIButton *voteBtn;
#end
Related
I have a TableView with 3 UILabel: title, author name and category and a UIImage. All cells should look similar to this layout:
Correct cell layout:
When the app starts for some reason some cells have the title UILabel alignment not as it should be:
After scrolling the TableView a few times, these cells end up with the proper alignment. I'm not quite sure what is causing this.
I have created a Custom TableView Cell class (followed this tutorial)
CustomTableViewCell.h
#interface CustomTableViewCell : UITableViewCell
#property (nonatomic, weak) IBOutlet UIImageView *image;
#property (nonatomic, weak) IBOutlet UILabel *titleLabel;
#property (nonatomic, weak) IBOutlet UILabel *authorLabel;
#property (nonatomic, weak) IBOutlet UILabel *categoryLabel;
#end
CustomTableViewCell.m
#implementation CustomTableViewCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}
- (void)awakeFromNib
{
// Initialization code
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void)layoutSubviews
{
[super layoutSubviews];
[self.contentView layoutIfNeeded];
self.titleLabel.preferredMaxLayoutWidth = CGRectGetWidth(self.titleLabel.frame);
[self.titleLabel sizeToFit];
[self.titleLabel setNumberOfLines:0];
}
#end
This is how this class is implemented in the ViewController:
#interface CurrentIssueViewController () {
CurrentIssueModel *_currentIssueModel;
Article *_selectedArticle;
}
#end
#implementation CurrentIssueViewController
static NSString *cellIdentifier = #"BasicCell";
UIActivityIndicatorView *activityView;
//#synthesize _feedItems;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(didChangePreferredContentSize:)name:UIContentSizeCategoryDidChangeNotification object:nil];
// Create array object and assign it to _feedItems variable
self._feedItems = [[NSArray alloc] init];
// Create new HomeModel object and assign it to _homeModel variable
_currentIssueModel = [[CurrentIssueModel alloc] init];
// Set this view controller object as the delegate for the home model object
_currentIssueModel.delegate = self;
// Call the download items method of the home model object
[_currentIssueModel downloadItems];
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIContentSizeCategoryDidChangeNotification object:nil];
}
- (void)didChangePreferredContentSize:(NSNotification *)notification
{
[self.tableView reloadData];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)itemsDownloaded:(NSArray *)items
{
// This delegate method will get called when the items are finished downloading
// Set the downloaded items to the array
self._feedItems = items;
[activityView stopAnimating];
// Reload the table view
[self.tableView reloadData];
}
#pragma mark Table View Delegate Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of feed items (initially 0)
return self._feedItems.count;
}
/* ================================================== */
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
[self configureCell:cell forRowAtIndexPath:indexPath];
return cell;
}
- (void)configureCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([cell isKindOfClass:[CustomTableViewCell class]])
{
CustomTableViewCell *textCell = (CustomTableViewCell *)cell;
Article *article_item = self._feedItems[indexPath.row];
NSString *fulltitle = article_item.Title;
if (article_item.Subtitle != nil && article_item.Subtitle.length != 0) {
fulltitle = [fulltitle stringByAppendingString:#": "];
fulltitle = [fulltitle stringByAppendingString:article_item.Subtitle];
}
textCell.titleLabel.text = fulltitle;
if ([article_item.Author isEqualToString:#"accountant"]) {
textCell.authorLabel.text = #"";
}
else {
textCell.authorLabel.text = article_item.Author;
}
textCell.categoryLabel.text = article_item.Cat_Name;
textCell.titleLabel.numberOfLines = 0;
textCell.titleLabel.font = [UIFont fontWithName:#"Arial" size:12.0f];
textCell.authorLabel.font = [UIFont fontWithName:#"Arial" size:10.0f];
textCell.categoryLabel.font = [UIFont fontWithName:#"Arial" size:10.0f];
textCell.categoryLabel.textAlignment = NSTextAlignmentRight;
NSURL *url;
if ([article_item.ImageUrl length] != 0) {
url = [NSURL URLWithString:article_item.ImageUrl];
}
else {
url = [NSURL URLWithString:#"imageurl"];
}
[textCell.image sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:#"default_image.jpg"]];
}
}
- (CustomTableViewCell *)prototypeCell
{
if (!_prototypeCell)
{
_prototypeCell = [self.tableView dequeueReusableCellWithIdentifier:cellIdentifier];
}
return _prototypeCell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
[self configureCell:self.prototypeCell forRowAtIndexPath:indexPath];
self.prototypeCell.bounds = CGRectMake(0.0f, 0.0f, CGRectGetWidth(self.tableView.bounds), CGRectGetHeight(self.prototypeCell.bounds));
[self.prototypeCell layoutIfNeeded];
CGSize size = [self.prototypeCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
return size.height+1;
}
/* ================================================== */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Set selected article to var
_selectedArticle = self._feedItems[indexPath.row];
[self performSegueWithIdentifier:#"detailSegue" sender:self];
}
#pragma mark Segue
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get reference to the destination view controller
ArticleViewController *articleVC = segue.destinationViewController;
// Set the property to the selected article so when the view for
// detail view controller loads, it can access that property to get the feeditem obj
articleVC.selectedArticle = _selectedArticle;
}
#end
I guess it's something to do with forRowAtIndexPath but I can't really figure out what's the issue.
Update:
I noticed that there is another problem with the title UILabel. Whenever you select a cell, view the article in another ViewController and go back to the UITableView the title labels are positioned in the Center Left rather than Top Left. Once you scroll again the title labels adjust to the proper position.
You have auto layout selected for the NIB/Storyboard but have not added any constraints to your cells. Add layout constraints to your cells. There is a great answer here that explains it in some details:
I have a tableView which I get the content from Parse.com (an image, one title and one description) and I am using a UIView for my detailView. When a cell is tapped UIView comes in with an animation. I managed to get My title and description of events but I couldn't get the Image file.
How to pass the parsed image into the UIView?
Thanks.
Here is my .h file
#import <UIKit/UIKit.h>
#import <Parse/Parse.h>
#import "TableCell.h"
#interface ViewController : UIViewController <UITableViewDelegate> {
NSArray *events;
}
#property (weak, nonatomic) IBOutlet UITableView *newsTable;
#property (strong, nonatomic) IBOutlet UIView *detailView;
#property (strong, nonatomic) IBOutlet UILabel *InfoDetailLabel;
- (IBAction)backBtn:(id)sender;
#property (strong, nonatomic) IBOutlet UILabel *viewTitle;
Here is the .m file
#import "ViewController.h"
#import "TableCell.h"
#import "Reachability.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize newsTable;
- (BOOL)connected
{
Reachability *reachability = [Reachability reachabilityForInternetConnection];
NetworkStatus networkStatus = [reachability currentReachabilityStatus];
return !(networkStatus == NotReachable);
}
- (void)viewDidLoad
{
[super viewDidLoad];
//Pull to refresh
UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
[refreshControl addTarget:self action:#selector(refresh:) forControlEvents:UIControlEventValueChanged];
[self.newsTable addSubview:refreshControl];
//Checking connection
if (![self connected])
{
// not connected
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Internet Connection Not Found" message:#"Please check your network settings!" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
} else
{
// connected, do some internet stuff
}
// Do any additional setup after loading the view, typically from a nib.
[self performSelector: #selector(retreiveFromParse)];
}
//pull to refresh
- (void)refresh:(UIRefreshControl *)refreshControl {
[refreshControl endRefreshing];
}
- (void) retreiveFromParse {
PFQuery *retrieveEvents = [PFQuery queryWithClassName:#"News"];
[retrieveEvents findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
events = [[NSArray alloc] initWithArray:objects];
}
[newsTable reloadData];
}];
}
//*********************Setup table of folder names ************************
//get number of sections in tableview
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
//get number of rows by counting number of folders
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return events.count;
}
//setup cells in tableView
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//setup cell
static NSString *CellIdentifier = #"EventCell";
TableCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
PFObject *tempObject = [events objectAtIndex:indexPath.row];
cell.TitleLabel.text = [tempObject objectForKey:#"Event"];
cell.DescriptionLabel.text = [tempObject objectForKey:#"Description"];
// To get the image file from Parse class
PFFile *imageFile = [tempObject objectForKey:#"imageFile"];
PFImageView *imageView = [[PFImageView alloc] init];
imageView.file = imageFile;
[imageView loadInBackground:^(UIImage *img,NSError *error){
if(!error)
{
UIImageView *yourImageView = [[UIImageView alloc] init];
yourImageView.image = imageView.image;
/*OR*/
cell.imageView.image = imageView.image;
}}];
return cell;
}
//user selects folder to add tag to
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"cell tapped");
//For detail view
PFObject *tempObject = [ events objectAtIndex:indexPath.row];
NSLog(#"%#", tempObject.objectId);
_InfoDetailLabel.text = [tempObject objectForKey:#"detailinformation"];
[self animateDetailView];
_viewTitle.text = [tempObject objectForKey:#"Event"];
[self animateDetailView];
}
//for animation of detailview
- (void) animateDetailView {
[UIView animateWithDuration:0.3 animations:^{
_detailView.frame = CGRectMake(0, 0, 320, 518);
}];
}
//back button with animation
- (IBAction)backBtn:(id)sender {
[UIView animateWithDuration:0.3 animations:^{
_detailView.frame = CGRectMake(320, 0, 320, 518);
}];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
and my cell .h
#import <UIKit/UIKit.h>
#import <Parse/Parse.h>
#interface TableCell : UITableViewCell
#property (strong, nonatomic) IBOutlet UILabel *TitleLabel;
#property (strong, nonatomic) IBOutlet UILabel *DescriptionLabel;
#property (strong, nonatomic) IBOutlet PFImageView *imageView;
#end
Try,
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"cell tapped");
//Assuming not reordering the cells after it loaded
TableCell *cell = (TableCell *)[tableView cellForRowAtIndexPath:indexPath];
[[yourDetailView imageView] setImage:[[cell imageView] image]];
.....
}
or you can use the same method loadInBackground: used in cellForRow in detailView also
Im making a program where im practicing UIPopoverController's for iPad
in the first popover i have a tableView with some cells , what i want to do is to call a new view with a textfield so i can add new cells with the textfield text .
The problem i have is that when i dismiss the second view the tableView is not updated . I can't call reloadData because the first view don't call "viewWillAppear" ou any other .
In the iphone simulator it works well because iphone don't use uiPopoverController but in iPad i have to dismiss the first popover and the view only reloads when i enter the second time.
I know by reading some posts that its possible to use notification center to make it happen but i don't know how
My code is this
-first view , the tableView
BNRAssetTypeViewController.h
#import <Foundation/Foundation.h>
#class BNRItem;
#interface BNRAssetTypeViewController : UITableViewController
#property (nonatomic,strong) BNRItem *item;
#property (nonatomic, copy) void (^dismissBlock)(void);
#end
BNRAssetTypeViewController.m
#import "BNRAssetTypeViewController.h"
#import "BNRItem.h"
#import "BNRItemStore.h"
#import "BNRDetailViewController.h"
#import "AddNewAssetedTypeViewController.h"
#implementation BNRAssetTypeViewController
-(instancetype)init
{
//Chamar o designated initializer
self = [super initWithStyle:UITableViewStylePlain];
if (self) {
//Titulo
UINavigationItem *navItem = self.navigationItem;
navItem.title=#"New Asseted Type";
//Criar um novo bar button que faz novo item do lado direito
UIBarButtonItem *bbi =[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
target:self action:#selector(addNewAssetedType)];
//meter do lado direito
navItem.rightBarButtonItem=bbi;
}
return self;
}
-(instancetype)initWithStyle:(UITableViewStyle)style
{
return [self init];
}
-(void)viewDidLoad
{
[super viewDidLoad];
NSLog(#"ViewDidLoad");
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:#"UITableViewCell"];
}
-(void)viewWillAppear:(BOOL)animated
{
NSLog(#"ViewwillApear");
[self.tableView reloadData];
}
-(void)viewDidAppear:(BOOL)animated{
NSLog(#"ViewDidApear");
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[[BNRItemStore sharedStore]allAssetTypes]count];
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"UITableViewCell" forIndexPath:indexPath];
NSArray *allAssetTypes = [[BNRItemStore sharedStore]allAssetTypes];
NSManagedObject *assetType = allAssetTypes[indexPath.row];
// Use key-value coding to get the asset type's label
NSString *assetLabel = [assetType valueForKey:#"label"];
cell.textLabel.text = assetLabel;
// Checkmark the one that is currently selected
if (assetType == self.item.assetType) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
} else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType=UITableViewCellAccessoryCheckmark;
NSArray *allAssets = [[BNRItemStore sharedStore]allAssetTypes];
NSManagedObject *assetType = allAssets[indexPath.row];
self.item.assetType=assetType;
if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad) {
self.dismissBlock();
} else {
[self.navigationController popViewControllerAnimated:YES];
}
}
-(void)addNewAssetedType{
AddNewAssetedTypeViewController *anatvc = [[AddNewAssetedTypeViewController alloc]init];
UINavigationController *navController = [[UINavigationController alloc]initWithRootViewController:anatvc];
navController.modalPresentationStyle=UIModalPresentationCurrentContext;
[self.navigationController presentViewController:navController animated:YES completion:nil];
}
-The second View
AddNewAssetedTypeViewController.h
#import <UIKit/UIKit.h>
#interface AddNewAssetedTypeViewController : UIViewController <UITextFieldDelegate>
#property (nonatomic,copy) void (^dismissBlock)(void);
#end
AddNewAssetedTypeViewController.m
#import "AddNewAssetedTypeViewController.h"
#import "BNRItemStore.h"
#import "BNRAssetTypeViewController.h"
#interface AddNewAssetedTypeViewController ()
#property (weak, nonatomic) IBOutlet UITextField *textField;
#end
#implementation AddNewAssetedTypeViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
UIBarButtonItem *doneItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone
target:self
action:#selector(save:)];
self.navigationItem.rightBarButtonItem=doneItem;
UIBarButtonItem *cancelItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemCancel
target:self action:#selector(cancel:)];
self.navigationItem.leftBarButtonItem=cancelItem;
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
-(void) viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[self.view endEditing:YES];
[[BNRItemStore sharedStore] createAssetType:self.textField.text];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)cancel:(id)sender
{
[self.presentingViewController dismissViewControllerAnimated:YES
completion:nil];
}
-(void)save:(id)sender
{
[self.presentingViewController dismissViewControllerAnimated:YES
completion:nil];
}
#end
Olá!
You can fire a notification using NSNotificationCenter when something is added in the popover. First, register the first view controller to observe for that notification. In the first VC retain a reference to the observer you'll register later on:
#implementation BNRAssetTypeViewController {
id _observer;
}
In viewWillAppear:
_observer = [[NSNotificationCenter defaultCenter] addObserverForName:#"somethingAddedNotification"
object:nil
queue:nil
usingBlock:^(NSNotification *notification)
{
[self.tableView reloadData];
}];
In viewWillDisappear:
- (void)viewWillDisappear:(BOOL)animated {
[[NSNotificationCenter defaultCenter] removeObserver:_observer];
}
Then in the method save: in the second view controller:
[[NSNotificationCenter defaultCenter] postNotificationName:#"somethingAddedNotification" object:nil];
Disclaimer: untested code. Let me know how it goes.
I am trying to add a simple button to a custom cell that has a web link. I added the button in story board and associated it with houseLink. Here is my view.M file where I call the button from the custom cell.
#import "IBSecondViewController.h"
#import "C21TableCell.h"
#interface IBSecondViewController ()
#end
#implementation IBSecondViewController
{
NSArray *thumbnails;
}
#synthesize data;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//Initialize House Array
data = [NSArray arrayWithObjects:#"2109 E Avon Cricle, Hayden Lake, ID", #"703 E Garden, Coeur d' Alene, ID", nil];
_bedroom = [NSArray arrayWithObjects:#"3", #"4", nil];
// Initialize thumbnails
thumbnails = [NSArray arrayWithObjects:#"stockHouse.png", #"stockHouse2.png", nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view ddata source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [data count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"C21TableCell";
C21TableCell *cell = (C21TableCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"C21TableCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.addressLabel.text = [data objectAtIndex:indexPath.row];
cell.bedroomLabel.text = [_bedroom objectAtIndex:indexPath.row];
cell.thumbnailImageView.image = [UIImage imageNamed:[thumbnails objectAtIndex:indexPath.row]];
NOT SURE HOW TO CALL THE BUTTON HERE
return cell;
}
-(void) buttonpressed:(UIButton *)sender {
NSString* launchUrl = #"http://apple.com/";
[[UIApplication sharedApplication] openURL:[NSURL URLWithString: launchUrl]];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 78;
}
#end
C21TableCell.H
#import <UIKit/UIKit.h>
#interface C21TableCell : UITableViewCell
#property (nonatomic, weak) IBOutlet UILabel *addressLabel;
#property (nonatomic, weak) IBOutlet UILabel *bedroomLabel;
#property (nonatomic, weak) IBOutlet UIImageView *thumbnailImageView;
#property (nonatomic, weak) IBOutlet UIButton *homeLink;
#end
C21TableCell.M
#import "C21TableCell.h"
#implementation C21TableCell
#synthesize addressLabel = _nameLabel;
#synthesize bedroomLabel = _bedroomLabel;
#synthesize thumbnailImageView = _thumbnailImageView;
#synthesize homeLink = homeLink;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}
- (void)awakeFromNib
{
// Initialization code
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
#end
Just add target to button action when you create cell
[cell.homeLink addTarget:self action:#selector(buttonpressed:) forControlEvents:UIControlEventTouchUpInside];
Hi I'm trying to reload my table view based off of two different arrays. Which array should be loaded is determined by a segment control in the navigation bar. Currently it only will load the first array and nothing happens when the segment control is pressed. Below is my code any help as to why this isn't working is greatly appreciated. I've also checked that my IBAction segmenter is connected in the nib.
MessageViewController.h
#import <UIKit/UIKit.h>
#interface MessageViewController : UIViewController<UITableViewDelegate> {
IBOutlet UISegmentedControl *segmentControl;
IBOutlet UINavigationBar *navBar;
IBOutlet UITableView *tableView;
}
#property (retain, nonatomic) IBOutlet UISegmentedControl *segmentControl;
#property (retain, nonatomic) IBOutlet UITableView *tableView;
#property (nonatomic, retain) NSMutableArray *inbox;
#property (nonatomic, retain) NSMutableArray *sent;
#end
MessageViewController.m
#import "MessageViewController.h"
#interface MessageViewController () <UITableViewDelegate>
#end
#implementation MessageViewController
#synthesize segmentControl;
#synthesize inbox;
#synthesize sent;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.tabBarItem.title = NSLocalizedString(#"Messages", #"Messages");
self.tabBarItem.image = [UIImage imageNamed:#"mail_2_icon&32"];
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView.delegate = self;
self.inbox = [NSMutableArray arrayWithObjects:#"testing", #"test", #"another", nil];
self.sent = [NSMutableArray arrayWithObjects:#"test", #"another", #"testing", nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
#pragma mark Table view methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if(segmentControl.selectedSegmentIndex == 0){
return [inbox count];
}else if(segmentControl.selectedSegmentIndex == 1){
return [sent count];
}else{
return [inbox count];
}
}
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
if(segmentControl.selectedSegmentIndex == 0){
NSString *cellValue = [inbox objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
}else if(segmentControl.selectedSegmentIndex == 1){
NSString *cellValue = [sent objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
}else{
NSString *cellValue = [inbox objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
}
return cell;
}
-(IBAction)segmenter{
[tableView reloadData];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
}
- (void)dealloc {
[inbox release];
[sent release];
[segmentControl release];
[segmentControl release];
[super dealloc];
}
- (void)viewDidUnload {
[self setSegmentControl:nil];
[segmentControl release];
segmentControl = nil;
[super viewDidUnload];
}
#end
Not sure why it wasn't working in the end all I did was delete the three classes and redo everything with the code above something must have just got borked along the way but it's working now and I'm a happy camper. Didn't need the delegate stuff either since that's all done in the nib so my original code worked fine.
set the delegate and datasource methods and take breakpoint to check the data . your code is right .
tableview.delegate=self;
tableView.datasource=self;
The only problem I see is that you're using a view controller with a table view in it, but you're not setting up the delegate for it in your viewDidLoad, and you're not implementing the delegate for your view controller.
#interface MessageViewController () <UITableViewDelegate, UITableViewDataSource>
#end
In viewDidLoad:
self.tableView.delegate = self;
self.tableView.dataSource = self;
Also make sure you have everything hooked up properly in IB, both your segmented control and your table view.
EDIT: I made my own test as per what you're trying to do, Here's my own implementation file