Create drop down menu with UITableView - ios

I am trying to build a drop down menu. When I click a button button I want a table view to open and then tap on the UITableViewCell. I want the cell data to display in the button
.h file
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
#interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>{
IBOutlet UITableView *tblSimpleTable;
IBOutlet UIButton *btn;
IBOutlet UIImageView *i;
BOOL flag;
NSArray *arryData;
}
#property(nonatomic,retain)IBOutlet UITableView *tblSimpleTable;
#property(nonatomic,retain)IBOutlet UIButton *btn;
#property(nonatomic,retain)IBOutlet UIImageView *i;
-(IBAction)btnClicked;
#end
.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize btn;
#synthesize tblSimpleTable;
#synthesize i;
-(IBAction)btnClicked{
if (flag==1) {
flag=0;
tblSimpleTable.hidden=NO;
i.hidden=YES;
}
else{
flag=1;
tblSimpleTable.hidden=YES;
i.hidden=NO;
}
}
// 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 {
}
*/
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
arryData = [[NSArray alloc] initWithObjects:#"iPhone",#"iPod",#"MacBook",#"MacBook Pro",nil];
//tblSimpleTable.frame =CGRectMake(10, 10, 300, 100);
flag=1;
tblSimpleTable.hidden=YES;
btn.layer.cornerRadius=8;
tblSimpleTable.layer.cornerRadius=8;
//i=[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"arrow-down.png"]];
[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 {
[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
// Release anything that's not essential, such as cached data
}
#pragma mark Table view methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [arryData count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] ;
}
// Set up the cell...
cell.textLabel.text = [arryData objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
}
#end

You can do it in your didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Changing button label
[_btn setTitle:[arryData objectAtIndex:indexPath.row] forState:UIControlStateNormal];
// Hiding table view
flag=1;
tblSimpleTable.hidden=YES;
i.hidden=NO;
}

Related

Display TableView from TextField and passing data

I'm learning Xcode and programming for the IPad. I have a TableView and can display it using a button. I would rather display it when I click on a TextField. If I dismiss the first responder, the keyboard, how then do I display the tableView? I have not found a example that fits. Any direction would help.
It is just simple
just in UItextField delegate method create your tableview.But return No ,that will never show keyboard and write your tableview code there.
here your have to use user defined delegates.
//firstViewController
***********************
#interface ViewController ()<UITextFieldDelegate,send>
{
UITextField *textField;
}
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
textField=[[UITextField alloc]initWithFrame:CGRectMake(20, 20, 160, 60)];
textField.delegate=self;
textField.backgroundColor=[UIColor greenColor];
[self.view addSubview:textField];
}
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
TableViewController *table=[[TableViewController alloc]initWithNibName:#"TableViewController" bundle:nil];
table.delegate=self;
[self presentViewController:table animated:YES completion:nil];
return NO;
}
-(void)clickedValue:(NSString *)name
{
textField.text=name;
}
//secondcontroller
*********************
in.h
#protocol send <NSObject>
#required
-(void)clickedValue:(NSString *)name;
#end
#interface........
#property (nonatomic, retain) id<send> delegate;
.m
******
#interface TableViewController ()
{
NSArray *arr;
}
#end
#implementation TableViewController
- (void)viewDidLoad
{
[super viewDidLoad];
arr=[[NSArray alloc]initWithObjects:#"murali",#"mohan",nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return arr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.text=[arr objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self.delegate clickedValue:[arr objectAtIndex:indexPath.row]];
[self dismissViewControllerAnimated:YES completion:nil];;
}

PopOverViewController ScreenSize Inconsistency

I have created a popover viewcontroller and size is 300*250, but once I click on popover button, it shows me a bigger than I define.
#import <UIKit/UIKit.h>
#interface ZDPopViewController : UIViewController
#property (strong, nonatomic) IBOutlet UITableView *zdTableView;
#property (strong, nonatomic) NSArray *tableData;
#property (strong,nonatomic) UIPopoverController * popoverController;
#end
#import "ZDPopViewController.h"
#interface ZDPopViewController ()
#end
#implementation ZDPopViewController
#synthesize zdTableView,tableData,popoverController;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
tableData=[[NSArray alloc]initWithObjects:#"TWT",#"TVD",#"TVDSS",#"FREQ", nil];
self.zdTableView.backgroundColor=[UIColor blackColor];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return [tableData count];
}
- (void)viewWillAppear:(BOOL)animated
{
self.popoverController.popoverContentSize = CGSizeMake(320, 220);
[super viewWillAppear:animated];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier=#"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
[cell.textLabel setText:[self.tableData objectAtIndex:indexPath.row]];
// Configure the cell...
return cell;
}
The simulated size does not define the size of the view controller, it is only used to show the view controller in the storyboard of that size.
To change the size of the use this in the view will appear of the View Controller-
- (void)viewWillAppear:(BOOL)animated
{
CGSize size = CGSizeMake(320, 200); // The size of view in popover you want
self.contentSizeForViewInPopover = size;
[super viewWillAppear:animated];
}
Try this post iOS 7 -
popoverController.popoverContentSize = CGSizeMake(320, 845);
Also Add -
[popoverViewController setPreferredContentSize:CGSizeMake(248.0,216.0)];
Repeat from Here

TableView UILabel alignment changes when scrolling

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:

Using a delegate to transfer data

I have a view controller with a static cell named 'Make' I have two controllers one called "AddCarTableViewController" and "MakeTableViewController" when you click on the static cell named 'Make' it presents the make table view controller where you can select the make, then pops the view controller and am trying to store the selected value in the detailTextLabel of the static cell. here is my code for all the controllers.
The problem I'm having is once I select the make everything happens as it should I even log the selected item and it saves it after popping the view controller, but I can't figure out how to implement selected item into the detailTextLabel. Any help will be much appreciated!
"MakeTableViewController.h"
#import <UIKit/UIKit.h>
#import "AddCarTableViewController.h"
#protocol CarMakeDelegate <NSObject>
- (void)updateCarMake:(NSString *)updateMake;
#end
#interface MakeTableViewController : UITableViewController
#property (nonatomic, strong) NSArray *carMakes;
#property (nonatomic, weak) id <CarMakeDelegate> delegate;
#end
MakeTableViewController.m
#import "MakeTableViewController.h"
#interface MakeTableViewController ()
#end
#implementation MakeTableViewController {
NSIndexPath *oldIndexPath;
}
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.carMakes = [[NSArray alloc] initWithObjects:#"Acura", #"Aston Martin", nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [self.carMakes count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
cell.textLabel.text = [self.carMakes objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:NO];
oldIndexPath = indexPath;
NSString *addMake = self.carMakes[indexPath.row];
[self.delegate updateCarMake:addMake];
NSLog(#"%#", addMake );
[[self navigationController] popViewControllerAnimated:YES];
}
#end
AddCarTableViewController.h
#import <UIKit/UIKit.h>
#import "MakeTableViewController.h"
#interface AddCarTableViewController : UITableViewController
#property (strong, nonatomic) NSString *makeName;
#property (weak, nonatomic) IBOutlet UITableViewCell *makeCell;
#end
AddCarTableViewController.m
#import "AddCarTableViewController.h"
#interface AddCarTableViewController ()
#end
#implementation AddCarTableViewController
- (void)viewDidLoad
{
[super viewDidLoad];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return 4;
}
-(void)updateCarMake:(NSString *)updateMake {
self.makeCell.detailTextLabel.text = updateMake;
}
#end
You don't need to use delegate in this case. Just update the underlying data model. and call
[tableview reloadData];
When the makeViewController is popped.
In the AddCarVC's cellForRowAtIndex, add another line to check if current indexPath corresponds to Make cell and if it does update the detailLabel text.

UITableViewCellStyle Custom iOS 7

I'm having a bit confusion with the UITableViewCellStyle. I want to create a custom UITableViewCell like this:
But the text and the image not appear in the cell when I run the app. In Storyboard,I've put the TableView Style to 'Custom'.
What am I doing wrong?
MainTableViewController
#import "MainTableViewController.h"
#import "CustomMainCell.h"
static NSString *CellIdentifier = #"MainCell";
#interface MainTableViewController ()
//
#property(nonatomic, strong) NSArray *dataSource;
//
#property(nonatomic, strong) NSArray *iconsSource;
#end
#implementation MainTableViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"Currículum Vitae";
// Inicializo los arrays con los datos
self.dataSource = #[#"PERFIL",#"EXPERIENCIA",#"EDUCACIÓN",#"HABILIDADES",#"INTERESES"];
self.iconsSource = #[#"perfil.png",#"experiencia.png",#"educacion.png",#"habilidades.png",#"intereses"];
// Register Class for Cell Reuse Identifier
[self.tableView registerClass:[CustomMainCell class] forCellReuseIdentifier:CellIdentifier];
// This will remove extra separators from tableview
self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
// Eliminio las líneas que separan las celdas
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CustomMainCell *cell = (CustomMainCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell == nil) {
cell = [[CustomMainCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell...
cell.title.text = self.dataSource[indexPath.row];
cell.icon.image = self.iconsSource[indexPath.row];
return cell;
}
CustomMainCell.h
#interface CustomMainCell : UITableViewCell
//
#property (weak, nonatomic) IBOutlet UILabel *title;
//
#property (weak, nonatomic) IBOutlet UIImageView *icon;
#end
CustomMainCell.m
#import "CustomMainCell.h"
#implementation CustomMainCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
self.textLabel.textColor = [UIColor brownColor];
}
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
You shouldn't have:
// Register Class for Cell Reuse Identifier
[self.tableView registerClass:[CustomMainCell class] forCellReuseIdentifier:CellIdentifier];
because the cell is registered from the storyboard when the view controller is unarchived. By registering the class you are removing the archive (NIB) registration.
Additionally:
if (cell == nil) {
cell = [[CustomMainCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
shouldn't be required as you will always get a valid cell back (because the identifier is registered)

Resources