After a some time, searching here for some solutions we found this post:
How to navigate through textfields (Next / Done Buttons)
We tried that but unfortunately it doesn't work at all. Note that we put the UITextFields inside a UITableView.
We think the problem is around the Delegates but we don't know how to deal with it. Following i show you our code:
.h:
#import <UIKit/UIKit.h>
#interface LoginViewController : UIViewController <UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate> {
UITableView *loginTableView;
UITextField *textField;
}
#property UITableView *loginTableView;
#property UITextField *textField;
#property UIButton *loginButton;
#property UIButton *cancelButton;
#end
.m:
#import <QuartzCore/QuartzCore.h>
#import "LoginViewController.h"
#import "RootViewController.h"
#interface LoginViewController ()
#end
#implementation LoginViewController
#synthesize loginTableView, textField, loginButton, cancelButton;
- (void)viewDidLoad {
[super viewDidLoad];
// Make rounded corners view
[self.view.layer setCornerRadius:4.0];
[self.view.layer setMasksToBounds:YES];
self.view.layer.opaque = NO;
self.view.backgroundColor = [UIColor whiteColor];
// Create background image view
UIImageView *loginBackgroundImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height+20)];
// Create background's image
UIImage *backgroundImage = [UIImage imageNamed:#"loginbackground.png"];
loginBackgroundImageView.image = backgroundImage;
[self.view addSubview:loginBackgroundImageView];
// Create logo's image
UIImage *logoImage = [UIImage imageNamed:#"logo.png"];
// Create logo's image view
UIImageView *logoImageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.bounds.size.width/2 - logoImage.size.width/2, self.view.bounds.size.height/9, logoImage.size.width, logoImage.size.height)];
// Set image to logo's image view
logoImageView.image = logoImage;
[self.view addSubview:logoImageView];
// Create login table view
loginTableView = [[UITableView alloc] initWithFrame:CGRectMake(self.view.bounds.size.width/2 - (self.view.bounds.size.width/1.2)/2, self.view.bounds.size.height/3, self.view.bounds.size.width/1.25, 100) style:UITableViewStylePlain
];
loginTableView.delegate = self;
loginTableView.dataSource = self;
// Create login container table view
UIImage *containerImage = [UIImage imageNamed:#"loginform.png"];
UIImageView *containerImageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.bounds.size.width/2 - containerImage.size.width/2, self.view.bounds.size.height/3, containerImage.size.width, containerImage.size.height)];
containerImageView.image = containerImage;
[self.view addSubview:containerImageView];
// Custom table view
loginTableView.backgroundColor = [UIColor clearColor];
loginTableView.separatorColor = [UIColor clearColor];
// Disable scroll
loginTableView.scrollEnabled = NO;
// Add login table view to main view
[self.view addSubview:loginTableView];
// Create buttons images
UIImage *loginImage = [UIImage imageNamed:#"loginbtn2.png"];
UIImage *cancelImage = [UIImage imageNamed:#"cancelbtn.png"];
// Create buttons
loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
// Set buttons' normal state image
[loginButton setImage:loginImage forState:UIControlStateNormal];
[cancelButton setImage:cancelImage forState:UIControlStateNormal];
// Place buttons
loginButton.frame= CGRectMake((self.view.bounds.size.width/2)-(loginImage.size.width/2), self.view.bounds.size.height/1.65, loginImage.size.width, loginImage.size.height);
cancelButton.frame= CGRectMake((self.view.bounds.size.width/2)-(cancelImage.size.width/2), self.view.bounds.size.height/1.375, cancelImage.size.width, cancelImage.size.height);
// Set buttons' action
[loginButton addTarget:self action:#selector(loginButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[cancelButton addTarget:self action:#selector(cancelButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
// Set button to the main view
[self.view addSubview:loginButton];
[self.view addSubview:cancelButton];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Cell"];
cell.accessoryType = UITableViewCellAccessoryNone;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
if ([indexPath section] == 0) {
textField = [[UITextField alloc] initWithFrame:CGRectMake(50, 11, 200, 25)];
textField.adjustsFontSizeToFitWidth = NO;
textField.textColor = [UIColor darkGrayColor];
textField.backgroundColor = [UIColor clearColor];
if ([indexPath row] == 0) {
textField.placeholder = #"Username";
textField.keyboardType = UIKeyboardTypeEmailAddress;
textField.returnKeyType = UIReturnKeyNext;
textField.autocorrectionType = UITextAutocorrectionTypeNo;
textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
textField.tag = 0;
}
else {
textField.placeholder = #"Password";
textField.keyboardType = UIKeyboardTypeEmailAddress;
textField.returnKeyType = UIReturnKeyDone;
textField.autocorrectionType = UITextAutocorrectionTypeNo;
textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
textField.secureTextEntry = YES;
textField.tag = 1;
}
textField.clearButtonMode = UITextFieldViewModeAlways;
textField.delegate = self;
[textField setEnabled: YES];
[cell addSubview:textField];
}
}
if ([indexPath section] == 0) { // Email & Password Section
if ([indexPath row] == 0) { // Email
cell.imageView.image = [UIImage imageNamed:#"usernameico.png"];
}
else {
cell.imageView.image = [UIImage imageNamed:#"passwordico.png"];
}
}
else { // Login button section
cell.textLabel.text = #"Log in";
}
return cell;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *) tableView {
return 1;
}
-(BOOL)textFieldShouldReturn:(UITextField*) formTextField {
NSInteger nextTag = formTextField.tag + 1;
// Try to find next responder
UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
if (nextResponder) {
// Found next responder, so set it.
[nextResponder becomeFirstResponder];
} else {
// Not found, so remove keyboard.
[formTextField resignFirstResponder];
}
return NO; // We do not want UITextField to insert line-breaks.
}
- (void)loginButtonPressed: (UIButton *) sender {
}
- (void)cancelButtonPressed: (UIButton *) sender {
}
#end
Thank you in advance!
The problem is the table. When you ask you text view for it's superview, it will return the cell, which doesn't contain any other siblings. Try:
UIResponder* nextResponder = [tableView viewWithTag:nextTag];
Creare an array with your UITextField inside the cellForRowAtIndexPath: method..
[txtArray addObject:textField];
and then this bellow method it will work...
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
int i=[txtArray count];
int x=textField.tag+1;
UITextField *nextTextField = (UITextField *)[txtArray objectAtIndex:x];
if (x<i-1) {
[nextTextField becomeFirstResponder];
} else {
[textField resignFirstResponder];
}
return YES;
}
i hope this help you...
Give tag to your textField one by one and use textField delegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
int NextTextField = textField.tag+1;
UITextField *txt = (UITextField *) [tableView viewWithTag:NextTextField];
[txt becomeFirstResponder];
return NO;
}
Related
how can i return keyboard on textfield while i have put the textfield on cell.contentview , i am using textfieldshouldreturn methodbut its not working So please tell me how can i solve it ?
this is my code for set textfield on tableview cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellidentitifier = #"cell";
UITableViewCell * cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellidentitifier];
if (cell ==nil)
{
cell = [tableView dequeueReusableCellWithIdentifier:cellidentitifier];
}
else
{
[cell prepareForReuse];
}
UIImageView *imgview = [[UIImageView alloc]initWithFrame:CGRectMake(30, 10, 70, 70)];
imgview.backgroundColor = [UIColor blackColor];
[cell.contentView addSubview:imgview];
UITextField *_nameTF = [[UITextField alloc]initWithFrame:CGRectMake(120, 10, 160, 22)];
_nameTF.placeholder =#"Client Name";
_nameTF.layer.borderWidth = 1.0;
[cell.contentView addSubview:_nameTF];
_nameTF = nil;
UITextField *_timeTF = [[UITextField alloc]initWithFrame:CGRectMake(120, 37, 160, 22)];
_timeTF.placeholder = #"Time";
_timeTF.layer.borderWidth= 1.0;
[cell.contentView addSubview:_timeTF];
_timeTF = nil;
UITextField *_PhoneTF = [[UITextField alloc]initWithFrame:CGRectMake(120, 64, 160, 22)];
_PhoneTF.placeholder = #"Phone";
_PhoneTF.layer.borderWidth= 1.0;
[cell.contentView addSubview:_PhoneTF];
_PhoneTF = nil;
return cell;
}
set delegates to textfield in cellForRowAtIndexPath as below, before return cell statement.
_nameTF.delegate = self;
_timeTF.delegate = self;
_PhoneTF.delegate = self;
and
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}
and to your viewcontroller set delegate as below in .h file
#interface myviewVC : UIViewController<UITextFieldDelegate>
I have to create a tableview with one of the cell having a scrollview with paging enabled and paging control in it. I have already tried following.
I have created a TableView Cell in IB which has two things in it
1.ScrollView
2.Page control and some labels placed at runtime on each page of scrollview, I have tested this scrollview and paging control in normal view and it works as expected.
I have following code in the ScrollViewCell.h
#import <UIKit/UIKit.h>
#interface ScrollViewCell : UITableViewCell<UIScrollViewDelegate>
{
UIPageControl* pageControl;
UIScrollView* scrollView;
BOOL pageControlBeingUsed;
}
#property (nonatomic, retain) IBOutlet UIScrollView* scrollView;
#property (nonatomic, retain) IBOutlet UIPageControl* pageControl;
- (IBAction)changePage;
#end
And following code in ScrollViewCell.m
#import "ScrollViewCell.h"
#implementation ScrollViewCell
#synthesize scrollView;
#synthesize pageControl;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString*)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
NSArray *colors = [NSArray arrayWithObjects:[UIColor redColor], [UIColor greenColor], [UIColor blueColor], nil];
for (int i = 0; i < colors.count; i++) {
CGRect frame;
frame.origin.x = self.scrollView.frame.size.width * i;
frame.origin.y = 0;
frame.size = self.scrollView.frame.size;
UIView *subview = [[UIView alloc] initWithFrame:frame];
subview.backgroundColor = [UIColor grayColor];
[self.scrollView addSubview:subview];
// add buttons
CGRect Frame= CGRectMake(frame.origin.x,frame.origin.y,200,50);
//set your x and y position whatever u want.
UIButton *Button = [UIButton buttonWithType:UIButtonTypeCustom];
Button.frame = Frame;
UIImage *Img = [UIImage imageNamed:#"second.png"];
[Button setBackgroundImage:Img forState:UIControlStateNormal];
[scrollView addSubview: Button];
// add text
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(frame.origin.x,frame.origin.y+60,200,50)];
label.textAlignment = UITextAlignmentCenter;
label.text = #"Here you write your text";
label.textColor = [UIColor blackColor];
[scrollView addSubview:label ];
[subview release];
}
self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * colors.count, self.scrollView.frame.size.height);
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void)scrollViewDidScroll:(UIScrollView *)sender {
if (!pageControlBeingUsed) {
// Switch the indicator when more than 50% of the previous/next page isvisible
CGFloat pageWidth = self.scrollView.frame.size.width;
int page = floor((self.scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
self.pageControl.currentPage = page;
}
}
- (IBAction)changePage {
// update the scroll view to the appropriate page
CGRect frame;
frame.origin.x = self.scrollView.frame.size.width * self.pageControl.currentPage;
frame.origin.y = 0;
frame.size = self.scrollView.frame.size;
[self.scrollView scrollRectToVisible:frame animated:YES];
pageControlBeingUsed = YES;
}
#end
I am loading this cell in the table view as follows
static NSString *CellIdentifier = #"ScrollViewCell";
ScrollViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[ScrollViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
return cell;
When I am running this app it shows an empty table with desired height but nothing in it.
Is my approach correct ? if yes whats missing ?
Thanks
Regards
Vishal
You are trying to add customize your UIScrollView in UITableViewCell class itself, i am not sure whether it will work.
instead try like this in your UITableView class cellForRowAtIndexPath,
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString * CellIdentifier = #"GroupButtonCell";
CustomCell * cell = (CustomCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
NSArray * customcellArray = [[NSBundle mainBundle]loadNibNamed:#"CustomCell" owner:self options:nil];
for(id customcellObject in customcellArray){
if([customcellObject isKindOfClass: [UITableViewCell class]]){
cell = (CustomCell *)customcellObject;
break;
}
}
}
// Customize your UIScrollView here..
[cell.scrollView setDelegate:self];
[cell.scrollView setPagingEnabled:YES];
NSArray *colors = [NSArray arrayWithObjects:[UIColor redColor], [UIColor greenColor],[UIColor blueColor], nil];
cell.scrollView.contentSize = CGSizeMake(cell.scrollView.frame.size.width * colors.count,cell.scrollView.frame.size.height);
for (int i = 0; i < colors.count; i++) {
CGRect frame;
frame.origin.x = cell.scrollView.frame.size.width * i;
frame.origin.y = 0;
frame.size = cell.scrollView.frame.size;
UIView *subview = [[UIView alloc] initWithFrame:frame];
subview.backgroundColor = [colors objectAtIndex:i];
[cell.scrollView addSubview:subview];
}
// Configure the cell...
return cell;
}
try this in ScrollViewCell.m
Inside init method.
[self.contentView addSubview:scrollView];
You should add scrollview on cell. Check M not sure. I dint got time to try in project.
I'm not sure if I am approaching this the correct way so I need some help. I have a table with 5 rows for data to be entered. After the user enters all the data there is a button on the navigation bar that will add the data to the arrays. I want to set up another view controller that displays all of the data that has been entered by the user. I hope this makes sense. Here's what I have so far.
- (void)viewDidLoad
{
[super viewDidLoad];
[self initWithStyle: UITableViewStyleGrouped];
self.navigationController.navigationBarHidden=NO;
//self.navigationItem.hidesBackButton = YES;
// Uncomment the following line to preserve selection between presentations.
//self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle: #"Done" style:UIBarButtonItemStylePlain target: self action: #selector(add)] autorelease];
course = [[NSMutableArray alloc] init];
date = [[NSMutableArray alloc] init];
scores = [[NSMutableArray alloc] init];
rating = [[NSMutableArray alloc] init];
slope = [[NSMutableArray alloc] init];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
#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 5;
}
- (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] autorelease];
cell.accessoryType = UITableViewCellAccessoryNone;
if ([indexPath section] == 0) {
if ([indexPath row] == 0) {
UITextField *playerTextField = [[UITextField alloc] initWithFrame:CGRectMake(110, 10, 185, 30)];
playerTextField.adjustsFontSizeToFitWidth = YES;
playerTextField.textColor = [UIColor blackColor];
playerTextField.placeholder = #"Required";
playerTextField.keyboardType = UIKeyboardTypeDefault;
playerTextField.returnKeyType = UIReturnKeyNext;
playerTextField.text = [course objectAtIndex:indexPath.row];
playerTextField.backgroundColor = [UIColor whiteColor];
playerTextField.textAlignment = UITextAlignmentRight;
[playerTextField setEnabled: YES];
[cell addSubview:playerTextField];
[playerTextField release];
}
else if([indexPath row] == 1){
UITextField *playerTextField = [[UITextField alloc] initWithFrame:CGRectMake(110, 10, 185, 30)];
playerTextField.adjustsFontSizeToFitWidth = YES;
playerTextField.textColor = [UIColor blackColor];
playerTextField.placeholder = #"Required";
playerTextField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
playerTextField.returnKeyType = UIReturnKeyDone;
playerTextField.text = [date objectAtIndex:indexPath.row];
playerTextField.backgroundColor = [UIColor whiteColor];
playerTextField.textAlignment = UITextAlignmentRight;
[playerTextField setEnabled: YES];
[cell addSubview:playerTextField];
[playerTextField release];
}
else if([indexPath row] == 2){
UITextField *playerTextField = [[UITextField alloc] initWithFrame:CGRectMake(110, 10, 185, 30)];
playerTextField.adjustsFontSizeToFitWidth = YES;
playerTextField.textColor = [UIColor blackColor];
playerTextField.placeholder = #"Required";
playerTextField.keyboardType = UIKeyboardTypeNumberPad;
playerTextField.returnKeyType = UIReturnKeyDone;
playerTextField.text = [scores objectAtIndex:indexPath.row];
playerTextField.backgroundColor = [UIColor whiteColor];
playerTextField.textAlignment = UITextAlignmentRight;
[playerTextField setEnabled: YES];
[cell addSubview:playerTextField];
[playerTextField release];
}
else if([indexPath row] == 3){
UITextField *playerTextField = [[UITextField alloc] initWithFrame:CGRectMake(110, 10, 185, 30)];
playerTextField.adjustsFontSizeToFitWidth = YES;
playerTextField.textColor = [UIColor blackColor];
playerTextField.placeholder = #"Required";
playerTextField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
playerTextField.returnKeyType = UIReturnKeyDone;
playerTextField.text = [rating objectAtIndex:indexPath.row];
playerTextField.backgroundColor = [UIColor whiteColor];
playerTextField.textAlignment = UITextAlignmentRight;
[playerTextField setEnabled: YES];
[cell addSubview:playerTextField];
[playerTextField release];
}
else if([indexPath row] == 4){
UITextField *playerTextField = [[UITextField alloc] initWithFrame:CGRectMake(110, 10, 185, 30)];
playerTextField.adjustsFontSizeToFitWidth = YES;
playerTextField.textColor = [UIColor blackColor];
playerTextField.placeholder = #"Required";
playerTextField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
playerTextField.returnKeyType = UIReturnKeyDone;
playerTextField.text = [slope objectAtIndex:indexPath.row];
playerTextField.backgroundColor = [UIColor whiteColor];
playerTextField.textAlignment = UITextAlignmentRight;
[playerTextField setEnabled: YES];
[cell addSubview:playerTextField];
[playerTextField release];
}
}
}
if ([indexPath section] == 0) {
if ([indexPath row] == 0) {
cell.textLabel.text = #"Course";
}
else if([indexPath row] == 1){
cell.textLabel.text = #"Date";
}
else if([indexPath row] == 2){
cell.textLabel.text = #"Score";
}
else if([indexPath row] == 3){
cell.textLabel.text = #"Rating";
}
else if([indexPath row] == 4){
cell.textLabel.text = #"Slope";
}
}
return cell;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
[course replaceObjectAtIndex:textField.tag withObject:textField.text];
[date replaceObjectAtIndex:textField.tag withObject:textField.text];
[scores replaceObjectAtIndex:textField.tag withObject:textField.text];
[rating replaceObjectAtIndex:textField.tag withObject:textField.text];
[slope replaceObjectAtIndex:textField.tag withObject:textField.text];
return YES;
}
Wouldn't it just be easier to put 5 text fields in a view? I don't understand why you put them in a table view... If you want them to be scrollable, you can always just wrap your entire view in a scrollview, but I wouldn't do this with a table. As far as I know, it's generally bad to use a table view for input. It's more like a way to provide a user a display of some data, e.g. an array of objects. Also, usually, if you're using an NSMutableArray as a data source, you would also want your table data source methods like tableView:numberOfRowsInSection: to return a value based on the size of the array, rather than a magic, hard coded number.
I also see you're doing a lot of work in the code. You can have Interface Builder do all this stuff for you: just make a new UIViewController subclass with a xib that goes by the same name, design it in Interface Builder, and write the logic in the .m file.
For example, let's say I have a subclass of UIViewController called MyViewController, which has a view with 1 button 'next' and 2 UITextFields, conveniently called dateTF and scoreTF. My .h file would look something like this:
#import <UIKit/UIKit.h>
#interface MyViewController : UIViewController {
IBOutlet UITextField *dateTF;
IBOutlet UITextField *scoreTF;
}
#property (nonatomic, retain) UITextField *dateTF;
#property (nonatomic, retain) UITextField *scoreTF;
- (IBAction)clickedNext:(id)sender;
#end
Here we have a placeholder for the action that will be called when the "next" button is pressed, and 2 outlets to the text fields to retrieve the data from them. I don't need an IBOutlet to the button because I won't edit it.
The .m file could look like this:
#import "MyViewController.h"
#implementation MyViewController
#synthesize dateTF
#synthesize scoreTF;
// called when the button is clicked
- (IBAction)clickedNext:(id)sender{
NSString * date = self.dateTF.text;
NSString * score = self.scoreTF.text;
// do something with this data, like put up a model and go to the next view
}
#end
This assumes I have a xib file that contains my UI. In the xib you'll also need to make a few connections (easily done with ctrl+click_and_drag from source to target, e.g. from button to File's Owner): you'll need to connect the 2 IBOutlets and the button to call the IBAction, and you should be good to go.
Hope this helps!
I use data dictionary in passing data to a new viewController and uncomment the codes in the .m:
/*
// The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
// Custom initialization
}
return self;
}
*/
and add the new parameter in my case a dictionary:
Supposed the name is passDataHereController and selectedNews was declared as NSDictionary in the .h
// Note that I added the withDataDictionary:(NSDictionary*)passedDataDictionary
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil withDataDictionary:(NSDictionary*)passedDataDictionary{
if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
// Custom initialization
self.selectedNews = passedDataDictionary;
}
return self;
}
Then in the controller where you are going to pass the data
//supposed dataTobePassed is already populated
passDataHereController *newView = [[passDataHereController alloc] initWithNibName:#"passDataHereController" bundle:nil withDataDictionary:dataTobePassed];
[self.navigationController pushViewController:newView animated:YES];
[newView release];
That's one way in passing data to another view, others may have simpler solutions.
Hope it helps.
I implemented the following method in my tableviewcontroller for showing favorites with empty star and filled star:
-(IBAction) tapped:(UIButton *)sender
{
if([sender isSelected])
{
//...
[sender setImage:[UIImage imageNamed:#"fav-empty.png"] forState:UIControlStateNormal];
[sender setSelected:NO];
}
else
{
//...
[sender setImage:[UIImage imageNamed:#"fav-filled.png"] forState:UIControlStateNormal];
[sender setSelected:YES];
NSLog(#"%#",sender);
}
}
and I tried to use in this part:
- (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] autorelease];
UILabel *recept_neve=[[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 40)];
[recept_neve setTag:1];
UIButton *kedvenc_btn=[UIButton buttonWithType:UIButtonTypeCustom];
[kedvenc_btn setImage:[UIImage imageNamed:#"fav-empty.png"] forState:UIControlStateNormal];//default appereance on the startup
kedvenc_btn.frame=CGRectMake(200, 20, 50, 50);
[kedvenc_btn setTag:2];
[kedvenc_btn addTarget:self action:#selector(tapped:) forControlEvents:UIControlEventTouchUpInside];
[[cell contentView] addSubview:recept_neve];
[[cell contentView] addSubview:kedvenc_btn];
//[(UILabel*) [[cell contentView] viewWithTag:1] setText:[receptek objectAtIndex:indexPath.section*blokk+1]];
//[(UIButton *) [cell contentView] viewWithTag:2];
}
// Configure the cell...
cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
[(UILabel*) [[cell contentView] viewWithTag:1] setText:[receptek objectAtIndex:indexPath.section*blokk+1]];
return cell;
}
My problem is that every fifth button in the cells are working as would be the same.
If I tap on the button(empty star) in the first cell, the result will be the following: the first button becoming filled-star, so far so good(the expected behaviour), but in the same time the sixth star becoming filled too. Or if I tap on the second one, the seventh star getting filled and vica versa...
I logged the buttons where I tapping , and I realised, that the memory adresses are equals in the case of buttons above mentioned.
Sorry about my english, and thanks a lot for every help in advance!
the problem was that you reused the buttons all the time.
I show you a sample working code to structure a customized UITableViewCell correctly...
Let's do it step by step.
Create a new class called MyObjTableViewCellForSelection and provide these methods. Adapt it to your needs!
#class MyObj;
#interface MyObjTableViewCellForSelection : UITableViewCell
{
MyObj *myObj;
UIImageView *imageView;
UILabel *titleLabel;
}
#property (nonatomic,strong) MyObj *myObj;
#property (nonatomic,strong) UIImageView *imageView;
#property (nonatomic,strong) UILabel *titleLabel;
#end
Then the implementation:
#implementation MyObjTableViewCellForSelection
#synthesize myObj;
#synthesize imageView;
#synthesize titleLabel;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
imageView = [[UIImageView alloc] initWithFrame: CGRectZero];
imageView.contentMode = UIViewContentModeScaleAspectFit;
[self.contentView addSubview: imageView];
titleLabel = [[UILabel alloc] initWithFrame: CGRectZero];
[titleLabel setFont:[UIFont systemFontOfSize:14.0]];
[titleLabel setTextColor:[UIColor blackColor]];
[titleLabel setHighlightedTextColor:[UIColor darkGrayColor]];
[titleLabel setLineBreakMode: UILineBreakModeWordWrap];
titleLabel.numberOfLines = 2;
[self.contentView addSubview: titleLabel];
}
return self;
}
-(void) layoutSubviews {
[super layoutSubviews];
[imageView setFrame:CGRectMake(8.0, 10.0, 20.0, 20.0)];
[titleLabel setFrame:CGRectMake(40.0, 1.0, 250.0, 40.0)]; //two lines
}
- (void)setMyObj:(MyObj *)myObjX {
if (myObjX != myObj) {
[myObj release];
[myObjX retain];
//myObj = myObjX; //only with ARC on
}
titleLabel.text = whatever you need accessing myObj
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
// selection has to be adapted to your structure
[super setSelected:selected animated:animated];
switch (myObj.selectedFlag) {
case MYOBJ_STATUS_UNSELECTED:
imageView.image = [UIImage imageNamed:#"EmptyBullet.png"];
break;
case MYOBJ_STATUS_SELECTED:
imageView.image = [UIImage imageNamed:#"GreyBullet.png"];
break;
default:
break;
}
#end
now in your view class you can finally do:
- (MyObj *)myObjForIndexPath:(NSIndexPath *)indexPath {
MyObj* tmpObj = get the corresponding object
return tmpObj;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
MyObjTableViewCellForSelection *cell = (MyObjTableViewCellForSelection *)[tableView dequeueReusableCellWithIdentifier:#"cellID"];
if (cell == Nil) {
cell = [[ECUTableViewCellForSelection alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cellID"];
}
cell.myObj = [self myObjForIndexPath:indexPath]; //the assignment calls setMyObj of CLASS ECUTableViewCellForSelection that you just declared
return cell;
}
So finally that's the clean way of doing it...
I am getting memory leak at text fiels please suggest me how to resolve it.
I written the code in init() as:
eventTextField = nil;
eventTextField = [[UITextField alloc]initWithFrame:CGRectMake(10, 15, 300, 50)];
eventTextField.placeholder = #"Event Name";
[eventTextField setFont:[UIFont boldSystemFontOfSize:14]];
eventTextField.returnKeyType = UIReturnKeyDone;
eventTextField.keyboardAppearance = UIKeyboardAppearanceDefault;//Showing leak at this line
eventTextField.keyboardType = UIKeyboardTypeDefault;
eventTextField.delegate=self;
and I released it in dealloc method.
and in cellForRowIndex I am adding it as subview.
- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MasterViewIdentifier"];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:#"MasterViewIdentifier"] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UIView* elementView = [[UIView alloc] initWithFrame:CGRectMake(20,170,320,280)];
elementView.tag = 0;
elementView.backgroundColor=[UIColor clearColor];
[cell.contentView addSubview:elementView];
[elementView release];
}
UIView* elementView = [cell.contentView viewWithTag:0];
elementView.backgroundColor=[UIColor clearColor];
for(UIView* subView in elementView.subviews)
{
[subView removeFromSuperview];
}
if(indexPath.section == 0 && indexPath.row == 0)
{
CorkItAppDelegate* appDelegate = (CorkItAppDelegate*)[[UIApplication sharedApplication] delegate];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
wineNameTitleLabel.numberOfLines = 0;
[wineNameTitleLabel setFont:[UIFont boldSystemFontOfSize:14]];
if(appDelegate.isNewWine == YES)
{
wineNameTitleLabel.textColor = [UIColor blackColor] ;
wineNameTitleLabel.text = appDelegate.getNewWineName;
}
else
{
if([event.eventWineName length]>0)
{
wineNameTitleLabel.textColor = [UIColor blackColor] ;
wineNameTitleLabel.text = event.eventWineName;
}
else
{
wineNameTitleLabel.text = #"Wine Name";
}
}
[elementView addSubview:wineNameTitleLabel];
}
else if(indexPath.section == 1)
{
if(isRightButton == YES)
{
eventTextField.enabled = NO;
}
else
{
eventTextField.enabled = YES;
}
if([event.eventName length] > 0)
{
eventTextField.text = event.eventName;
}
else
{
eventTextField.text = #"";
}
[elementView addSubview:eventTextField];
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
Hope I get wucik response from your side.
Thanks in advance,
Monish.
If you still need the eventTextField. You should create a property and instance variable for it. So that, you can your class own the eventTextField and release it in the dealloc. Like this:
#interface A {
UITextField *eventTextField;
}
#property (nonatomic, retain) UITextField *eventTextField;
#end
#implementation A
#synthesize eventTextField;
- (id)init {
eventTextField = [[UITextField alloc]init];
}
- (void)dealloc {
[eventTextField release];
}
#end
you should release the UITextField after adding it to the subview
[foo addSubview:eventTextField];
[eventTextField release];
eventTextField = nil; is unnecessary btw as eventTextField is a ivar is already zeroed (pointer set to 0x0(nil))