My UIScrollView is not responding to touch events, nor is my touchesBegain method being called for my UIViewController. (Also the text on my buttons are distorted on one and not shown on the other)
In Storyboard I added the ScrollView to the UIViewController and added my UITextFields and UIButtons to the ScrollView
Here is the code:
#import <UIKit/UIKit.h>
#interface RefineSearchViewController : UIViewController <UITextFieldDelegate, UIScrollViewDelegate>
{
IBOutlet UIScrollView *scroller;
}
#property (strong, nonatomic) IBOutlet UITextField *nameField;
#property (strong, nonatomic) IBOutlet UITextField *targetField;
#property (strong, nonatomic) IBOutlet UITextField *vendorField;
#property (strong, nonatomic) IBOutlet UITextField *CATField;
#property (strong, nonatomic) IBOutlet UITextField *clonalityField;
#property (strong, nonatomic) IBOutlet UITextField *sourceOrganismField;
-(IBAction) textFieldReturn: (id) sender;
#import "RefineSearchViewController.h"
#import "DBHandler.h"
#interface RefineSearchViewController ()
#end
#implementation RefineSearchViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[scroller setScrollEnabled:YES];
// set the content size to be the size our our whole frame
//scroller.frame = CGRectMake(74, 261, 620, 354);
[scroller setContentSize:CGSizeMake(2000, 2000)];
[scroller setCanCancelContentTouches:NO];
[super viewDidLoad];
// Do any additional setup after loading the view.
self.targetField.delegate = self;
self.nameField.delegate = self;
self.vendorField.delegate = self;
self.clonalityField.delegate = self;
self.sourceOrganismField.delegate = self;
self.CATField.delegate = self;
}
-(void) viewWillAppear:(BOOL)animated
{
self.navigationController.navigationBarHidden = YES;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// If you are going to conduct a refine search
if ([[segue identifier] isEqualToString:#"Refine"])
{
DBHandler *handler = [[DBHandler alloc]init];
//Run searches on each of the parameter that aren't empty
NSString *nameParameter = _nameField.text;
if (![nameParameter isEqualToString:#""])
{
[handler search:0 andInput:nameParameter];
}
NSString *targetParameter = _targetField.text;
if(![targetParameter isEqualToString:#""])
{
[handler search:1 andInput:targetParameter];
}
NSString *vendorParameter = _vendorField.text;
if (![vendorParameter isEqualToString:#""])
{
[handler search:2 andInput:vendorParameter];
}
NSString *catParameter = _CATField.text;
if (![catParameter isEqualToString:#""])
{
[handler search:3 andInput:catParameter];
}
NSString *clonalityField = _clonalityField.text;
if (![catParameter isEqualToString:#""])
{
[handler search:4 andInput:clonalityField];
}
NSString *sourceField = _sourceOrganismField.text;
if (![sourceField isEqualToString:#""])
{
[handler search:5 andInput:sourceField];
}
//recursive implementation
for (int i = 0; i < 6 ; i++)
{
}
//We shouldn't clear the text fields here in my personal opinion because they apply to the search until you return to the homescreen and reset what is the
//current "working database"
}
//if you are going to cancel the refine search, simply go back to the previous screen
else if ([[segue identifier] isEqualToString:#"Cancel"])
{
//Do Nothing
//but more importantly....
//....clear Text Fields
_nameField.text = #"";
_targetField.text = #"";
_vendorField.text = #"";
_CATField.text = #"";
_clonalityField.text = #"";
_sourceOrganismField.text = #"";
}
}
//make that stubborn keyboard go away whenever you touch the background
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[_nameField resignFirstResponder];
[_targetField resignFirstResponder];
[_vendorField resignFirstResponder];
[_CATField resignFirstResponder];
[_clonalityField resignFirstResponder];
[_sourceOrganismField resignFirstResponder];
}
-(IBAction)textFieldReturn:(id)sender
{
[sender resignFirstResponder];
}
//following code was taken and tweaked from stack overflow
//- (void)textFieldDidBeginEditing:(UITextField *)textField
//{
// [self animateTextField: textField up: YES];
// NSLog(#"YO");
//}
//
//
//- (void)textFieldDidEndEditing:(UITextField *)textField
//{
// [self animateTextField: textField up: NO];
//}
//
//- (void) animateTextField: (UITextField*) textField up: (BOOL) up
//{
// const int movementDistance = 216; //height of the keyboard
// const float movementDuration = 0.3f; // duration of the animation
//
// int movement = (up ? -movementDistance : movementDistance);
//
// [UIView beginAnimations: #"anim" context: nil];
// [UIView setAnimationBeginsFromCurrentState: YES];
// [UIView setAnimationDuration: movementDuration];
// self.view.frame = CGRectOffset(self.view.frame, 0, movement);
// [UIView commitAnimations];
//}
#end
Make sure your scrollView's delegate is set properly in storyboard and scrollView's userInteractionEnabled is set.
Related
I want to change label.text but when I do it and check it with a NSLog it returns me a (null).
Here's my code:
NextViewController.h
#interface NextViewController (){
NSTimer *timerTen;
NSInteger countDown;
NSString *timer;
}
#end
#implementation NextViewController
static UILabel *lblTest;
- (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)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)startCountDown{
countDown = 10;
timerTen = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(dismissView) userInfo:nil repeats:YES];
}
-(void)dismissView{
timer = [NSString stringWithFormat:#"%ld", (long)countDown];
_lbl_countDown.text = timer;
NSLog(#"\nCountDown: %#\n", self.lbl_countDown.text);
countDown--;
if (countDown <= 0) {
SectionViewController *sectionView = [[SectionViewController alloc] init];
[sectionView.presentedViewController dismissViewControllerAnimated:YES completion:nil];
}
}
Then I have a XIB file with a label and more things, so I've used a prop right there in the .h to change it from other classes, but I can't change it.
NextViewController.h
#import <UIKit/UIKit.h>
#interface NextViewController : UIViewController
#property (strong, nonatomic) IBOutlet UILabel *lbl_section;
#property (strong, nonatomic) IBOutlet UILabel *lbl_nextSection;
#property (strong, nonatomic) IBOutlet UILabel *lbl_countDown;
-(void)startCountDown;
#end
Hope anyone can help me cause I don't know what is happening here.
Thanks.
Call your method in ViewDidLoad or ViewWillAppear
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
[self startCountDown]
}
OR
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self startCountDown]
}
Try to call the function first using [self startCountDown] in the ViewDidLoad method
if the problem persist:
Try to use this : [_lbl_count setText#"myText"];
In the Identity Inspector, click on the label uncheck the 'Static Text' and check 'Enabled' and 'User Interaction Enabled'
Finally check that your variable timer is not null after your initialization.
timer = [NSString stringWithFormat:#"%ld", (long)countDown];
Hope that will be helpfull
I wrote this code to use a button tap to start a countdown from 10 to a segue:
In my h:
#property (strong, nonatomic) IBOutlet UILabel *countdownCounter;
#property (strong, nonatomic) IBOutlet UIButton *countdownStarter;
In my m:
static NSTimer *timer;
static int remainingCounts;
.
.
-(void)countDown
{
if (--remainingCounts == 0)
{
[timer invalidate];
timer = nil;
[self performSegueWithIdentifier:#"FromStartToBalancer" sender:self];
}
else
{
NSString * holdText = [NSString stringWithFormat:#"%d", remainingCounts];
[self.countdownCounter setText:holdText];
}
}
- (IBAction)goToBalancerPressed:(UIButton *)sender
{
self.countdownStarter.userInteractionEnabled = NO;
self.countdownStarter.alpha = .3;
remainingCounts = 10;
timer = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:#selector(countDown)
userInfo:nil
repeats:YES];
}
I have a simple notes app where I have just 2 view controllers:
table view controller - to list all the notes.
view controller - to create new notes.
In the table view controller I have a segue from a cell back to the creation page where a user can edit the note in this specific cell.
But my problem is that when I'm preforming editing to a certain cell(note) I'm creating a new note with the content of what I edited...
So instead of passing the note content in the prepareForSegue method I need to pass the note object...
How can I do that?
this are my classes:
NMNote: (correctly just containing a property of *content, will add more behaviour later)
#import <Foundation/Foundation.h>
#interface NMNote : NSObject
#property (strong, nonatomic) NSString *content;
#end
NMCreateNotesViewController.h:
#import <UIKit/UIKit.h>
#import "NMNote.h"
#interface NMCreateNotesViewController : UIViewController
#property (strong, nonatomic) NMNote *note;
#property (weak, nonatomic) IBOutlet UITextView *textField;
#property (strong, nonatomic) NSString *passedInString;
#end
NMCreateNotesViewController.m:
#import "NMCreateNotesViewController.h"
#import "NMNotesListViewController.h"
#interface NMCreateNotesViewController () <UITextViewDelegate>
#property (weak, nonatomic) IBOutlet UIBarButtonItem *saveButton;
#end
#implementation NMCreateNotesViewController
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
// listen for keyboard hide/show notifications so we can properly adjust the table's height
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
}
#pragma mark - Notifications
- (void)adjustViewForKeyboardReveal:(BOOL)showKeyboard notificationInfo:(NSDictionary *)notificationInfo
{
// the keyboard is showing so ƒ the table's height
CGRect keyboardRect = [[notificationInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
NSTimeInterval animationDuration =
[[notificationInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
CGRect frame = self.textField.frame;
// the keyboard rect's width and height are reversed in landscape
NSInteger adjustDelta = UIInterfaceOrientationIsPortrait(self.interfaceOrientation) ? CGRectGetHeight(keyboardRect) : CGRectGetWidth(keyboardRect);
if (showKeyboard)
frame.size.height -= adjustDelta;
else
frame.size.height += adjustDelta;
[UIView beginAnimations:#"ResizeForKeyboard" context:nil];
[UIView setAnimationDuration:animationDuration];
self.textField.frame = frame;
[UIView commitAnimations];
}
- (void)keyboardWillShow:(NSNotification *)aNotification
{
[self adjustViewForKeyboardReveal:YES notificationInfo:[aNotification userInfo]];
}
- (void)keyboardWillHide:(NSNotification *)aNotification
{
[self adjustViewForKeyboardReveal:NO notificationInfo:[aNotification userInfo]];
}
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if (sender != self.saveButton) return;
if (self.textField.text.length > 0) {
self.note = [[NMNote alloc] init];
self.note.content = self.textField.text;
}
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
if (self.passedInString != nil) {
self.textField.text = self.passedInString;
}
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
NMNotesListViewController.h:
#import <UIKit/UIKit.h>
#interface NMNotesListViewController : UITableViewController
- (IBAction) unwindToList: (UIStoryboardSegue *) segue;
#end
NMNotesListViewController.m:
#import "NMNotesListViewController.h"
#import "NMCreateNotesViewController.h"
#interface NMNotesListViewController ()
#property (strong, nonatomic) NSMutableArray *notes;
#end
#implementation NMNotesListViewController
- (IBAction) unwindToList: (UIStoryboardSegue *) segue
{
NMCreateNotesViewController *source = [segue sourceViewController];
NMNote *note = source.note;
if (note != nil) {
[self.notes addObject:note];
[self.tableView reloadData];
}
}
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.notes = [[NSMutableArray alloc] init];
// 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 = self.editButtonItem;
}
- (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.notes count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"NotesPrototypeCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
NMNote *note = [self.notes objectAtIndex:indexPath.row];
cell.textLabel.text = note.content;
return cell;
}
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(UITableViewCell *)sender
{
if ([[segue identifier] isEqualToString:#"noteSegue"]) {
NMCreateNotesViewController *destination = [segue destinationViewController];
NSInteger indx = [self.tableView indexPathForCell:sender].row;
NMNote *note = self.notes[indx];
destination.passedInString = note.content;
}
}
//#pragma mark - delegate
//
//- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
//{
//
//}
#end
This is the screens flow:
the initiate view is this table view:
Now there is the TextView where you write the note:
Now, after you save a note, you go back to the first screen. and then you can tap on a populated cell and you will segue back to this screen (the one with the TextView) so you can edit it. But instead of editing it, it will create a new one with the edited content. like this:
Please, would appreciate any help here to accomplish my task..
Thanks!
The thing you need to do when you pass the note to the NMCreateNotesViewController, is to differentiate between an edit and an add action so when you came back to the table view, you can either replace the old entry with the new edited one, or add a new entry.
The way I would approach this is to have two segues, one from the + button (I'll call it "addSegue") and one from the table view cell (call it "editSegue"). I would also create a property in the list controller to hold the value of the edited row, or set it to something like -1 to indicate it's a new note. Something like this,
#property (nonatomic) NSInteger editedRow;
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"editSegue"]) {
NMCreateNotesViewController *destination = [segue destinationViewController];
NSInteger indx = [self.tableView indexPathForCell:(UITableViewCell *)sender].row;
self.editedRow = index;
NMNote *note = self.notes[indx];
destination.note = note;
}else if ([segue.identifier isEqualToString:#"addSegue"]) {
self.editedRow = -1;
}
The prepareForSegue method in the NMCreateNotesViewController would be the same as you have in your question. You can get rid of the passedInString property since we're passing in the entire note object instead. In the unwind method in the list controller, you would do this,
- (IBAction) unwindToList: (UIStoryboardSegue *) segue {
NMCreateNotesViewController *source = [segue sourceViewController];
NMNote *note = source.note;
if (note != nil && self.editedRow == -1) {
[self.notes addObject:note];
}else{
[self.notes replaceObjectAtIndex:self.editedRow withObject:note];
}
[self.tableView reloadData];
}
in NMCreateNotesViewController.h:
#property (strong, nonatomic) NMNote *note;
#property BOOL adding;
#property (strong,nonatomic) NSString *originalContent;
Then in your NMNotesListViewController.m prepareForSegue
destination.note=self.notes[indx];
destination.adding=NO; // set adding to yes if you are adding a new note
and in your unwind
- (IBAction) unwindToList: (UIStoryboardSegue *) segue
{
NMCreateNotesViewController *source = [segue sourceViewController];
NMNote *note = source.note;
if (source.adding && note != nil) {
[self.notes addObject:note];
[self.tableView reloadData];
}
}
in NMCreateNotesViewController.m
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
// listen for keyboard hide/show notifications so we can properly adjust the table's height
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
if (self.note != nil)
{
self.originalContent=self.note.content;
self.textField.text=self.note.content;
}
}
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if (sender != self.saveButton)
{
if (self.note != nil)
{
self.note.content=self.originalContent;
}
}
else
{
if (self.note == nil)
{
if (self.textField.text.length > 0) {
self.note = [[NMNote alloc] init];
}
self.note.content = self.textField.text;
}
}
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
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I am trying to learn how to get a button (in my case, a 'Cancel' button) to direct me back to the previous page it was on. I've got a button on my previous page that directs me to this page, and i want this button to take me back to the previous page and discard anything i had written on the page. My button on my first page pushes the view to this page through a modal connection. I know it would make sense to just use the simple modal connection for the Cancel button to get back to my original page, but I was hoping for a more elegant way to do this. Creating a custom view is a good idea i'm sure but I don't really know what to do there so.. haha but any suggestions would be greatly appreciated!
#import "AddEventViewController.h"
#import <QuartzCore/QuartzCore.h>
#interface AddEventViewController ()
#property (weak, nonatomic) IBOutlet UITextField *textField1;
#property (weak, nonatomic) IBOutlet UITextField *textField2;
#property (weak, nonatomic) IBOutlet UITextField *textField3;
#property (strong, nonatomic) IBOutlet UIScrollView *myScrollView;
#property (weak, nonatomic) IBOutlet UINavigationBar *addEventTitleBar;
#property (weak, nonatomic) IBOutlet UIBarButtonItem *cancelButton;
#property (weak, nonatomic) IBOutlet UIBarButtonItem *saveButton;
#property (weak, nonatomic) IBOutlet UITextView *myTextView;
- (IBAction)textFieldReturn:(id)sender;
#end
#implementation AddEventViewController
#synthesize textField1, textField2, textField3, myTextView;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (IBAction)textFieldReturn:(id)sender;
{
[sender resignFirstResponder];
}
- (void)viewDidLoad
{ // Do any additional setup after loading the view.
[super viewDidLoad];
self.textField1.delegate = self;
textField1.delegate = self;
self.textField2.delegate = self;
textField2.delegate = self;
self.textField3.delegate = self;
textField3.delegate = self;
[myTextView.layer setCornerRadius:10.0f];
[myTextView.layer setBorderColor:[UIColor lightGrayColor].CGColor];
[myTextView.layer setBorderWidth:1.5f];
[myTextView.layer setShadowColor:[UIColor blackColor].CGColor];
[myTextView.layer setShadowOpacity:0.002f];
[myTextView.layer setShadowRadius:3.0f];
[myTextView.layer setShadowOffset:CGSizeMake(2.0, 2.0)];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)touchesBegan: (NSSet *) touches withEvent: (UIEvent *)event
{
if (textField1)
{
if ([textField1 canResignFirstResponder]) [textField1 resignFirstResponder];
}
[super touchesBegan: touches withEvent: event];
if (textField2)
{
if ([textField2 canResignFirstResponder]) [textField2 resignFirstResponder];
}
[super touchesBegan: touches withEvent: event];
if (textField3)
{
if ([textField3 canResignFirstResponder]) [textField3 resignFirstResponder];
}
[super touchesBegan: touches withEvent: event];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
if (textField == textField1)
{
[textField1 resignFirstResponder];
}
else if (textField == textField2)
{
[textField2 resignFirstResponder];
}
else if (textField == textField3)
{
[textField3 resignFirstResponder];
}
return YES;
}
-(void)addCancelButton
{
UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithTitle:#"Cancel"style:UIBarButtonSystemItemAction target:self action:#selector(cancel:)];
self.navigationItem.leftBarButtonItem = cancelButton;
}
-(void)cancel:(id)sender
{
[self.navigationController dismissViewControllerAnimated:YES completion:nil];
[self.navigationController popViewControllerAnimated:NO];
}
#end
Fixed the issue!
You could solve it like this:
- (void)addCancelButton{
UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithTitle:#"Cancel"
style:UIBarButtonSystemItemCancel target:self action:#selector(cancel:)];
self.navigationItem.leftBarButtonItem = cancelButton;
}
- (void)cancel:(id)sender{
//If presented
[self.navigationController dismissViewControllerAnimated:YES completion:nil];
//If pushed
[self.navigationController popViewControllerAnimated:NO];
}
Where the code in AddCancelButton can be moved to viewDidLoad or somewhere appropriate. And you might want to edit how the view is removed depending on how it was added (pushed, presented etc.)
I have found a lot of sample code from internet, but also doesn't work.... anyone can tell me what's wrong of my coding below? thanks a lot. SOS
//My storeboard screen
http://imageupload.org/en/file/209300/03.jpg.html
//This is PickerViewTest.h
#interface InputRound : UIViewController<UITextFieldDelegate>
{
UIPickerView *pvPickerTest;
NSMutableArray *aryMaster;
}
#property (nonatomic, retain) IBOutlet UIPickerView *pvPickerTest;
#property (nonatomic, retain) NSMutableArray *aryMaster;
#end
//This is PickerViewTest.m
#interface InputRound ()
#end
#implementation PickerViewTest
#synthesize pvPickerTest, aryMaster;
-(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.
aryMaster = [[NSMutableArray alloc] init];
[aryMaster addObject:#"User01"];
[aryMaster addObject:#"User02"];
[aryMaster addObject:#"User03"];
}
-(NSInteger)numberOfComponentsInPickerView:(NSInteger)component
{
return 1;
}
-(NSInteger)pickerView:(UIPickerView *)picker numberOfRowsInComponent:(NSInteger)component
{
return [aryMaster count];
}
-(NSString *) pickerView:(UIPickerView *)picker titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return [aryMaster objectAtIndex:row];
}
-(void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
// Show UIPickerView
pvPickerTest.frame = CGRectMake(0, 500, pvPickerTest.frame.size.width, pvPickerTest.frame.size.height);
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:.50];
[UIView setAnimationDelegate:self];
pvPickerTest.frame = CGRectMake(0, 200, pvPickerTest.frame.size.width, pvPickerTest.frame.size.height);
[self.view addSubview:pvPickerTest];
[UIView commitAnimations];
return NO;
}
#end
Don't try and reinvent the wheel by rolling your own appearance animation to mimic the built in one. Set the picker view as the input view for your text field, and the system will do the animation for you:
textField.inputView = pickerView;
When you begin editing the text field, the picker is animated on screen for you. See my answer here for more details, including adding a toolbar on top with a "Done" button.