Tableview display alert error - ios

I am writing a simple tableview app, when tapping the row, a alert shows up.
(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *rowValue =self.greekLetters[indexPath.row];
// NSString *message=[[NSString alloc] initWithFormat:#"You selected%#!",rowValue];
if (indexPath.row==0) {
NSString *message=[[NSString alloc] initWithFormat:#"This is course aaaaa",rowValue];
}
if (indexPath.row==1) {
NSString *message=[[NSString alloc] initWithFormat:#"This is course aaaaa"];
}
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:#"Course introduction" message:message delegate:nil cancelButtonTitle:#"Return to courses list" otherButtonTitles:nil, nil];
[alert show];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
However, Xcode doesn't like my if statement here, while the following statement works.
NSString *message=[[NSString alloc] initWithFormat:#"You selected%#!",rowValue];
Could anyone give me an example of how to use the message here please?

This is a problem with scope. You need to declare message before the if statement:
NSString *message;
if (indexPath.row==0) {
message=[[NSString alloc] initWithFormat:#"This is course aaaaa",rowValue];
}
else if (indexPath.row==1) {
message=[[NSString alloc] initWithFormat:#"This is course aaaaa"];
}
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:#"Course introduction" message:message delegate:nil cancelButtonTitle:#"Return to courses list" otherButtonTitles:nil];
[alert show];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
However, if the course number is determined by the row number do:
NSString *rowValue =self.greekLetters[indexPath.row];
NSString *message = [[NSString alloc] initWithFormat:#"This is course %#",rowValue];
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:#"Course introduction" message:message delegate:nil cancelButtonTitle:#"Return to courses list" otherButtonTitles:nil];
[alert show];
[tableView deselectRowAtIndexPath:indexPath animated:YES];

You've forgotten to include %# in the first if-statement.
NSString *message= [[NSString alloc] initWithFormat:#"This is course aaaaa %#",rowValue];
By the way, there's no need to do [[NSString alloc] init] at all, just use [NSString stringWithFormat:...]

Related

UIAlertView confirm delete button

I have a tableview, and a delete function. Now I want an UIAlertView with a confirmation.
This is my code what I have now:
(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
AgendaModel* agenda = _meeting.agenda[indexPath.row] ;
NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:agenda.id,#"id",agenda.name,#"name", nil];
NSString *message = [NSString stringWithFormat:#"Are you sure that you want to delete : %#?", agenda.name];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Warning"
message:message
delegate:self
cancelButtonTitle:#"Close"
otherButtonTitles:#"Delete", nil];
[alert show];
}
}
It give's a popup, but because I didn't say to delete it isn't working. I want my app to do this code after the button Delete is pressed:
NSString *delete_url = [NSString stringWithFormat:#"RestAgendas/delete.json"];
[_meeting.agenda removeObject:agenda];
[self.tableView deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[JSONAPI getWithPath:delete_url andParams:dict completion:^(id json, JSONModelError *err) {
NSLog(#"%#", json);
}];
Where can I define actions to buttons in a UIAlertView?
Sorry for the messy question, hope you guys understand my intentions
You should avoid using AlertView (it's deprecated) and switch to UIAlertController.
It is more generic and replaces old alertView and actionSheet.
See the documetation
and tutorial in swift or tutorial in objC.

iPad search display controller displaying results starting in second cell

I added a Searchbar and Search Display Controller to my iPad app that use localSearch. I believe I implemented the delegates correctly. The search works fine and displays the results but the issues is that these results start in the second cell. The first cell in the popup display being empty. I double checked to see if the map items count and contents were correct and they were.
The code:
- (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
if (![self connected]) {
[[[UIAlertView alloc] initWithTitle:NSLocalizedString(#"Cannot Connect",nil)
message:NSLocalizedString(#"Please make sure you are connected to the internet and try again.",nil)
delegate:nil
cancelButtonTitle:NSLocalizedString(#"OK",nil) otherButtonTitles:nil] show];
}
else if ([mainToolbar isHidden])
{
[[[UIAlertView alloc] initWithTitle:NSLocalizedString(#"Search Unavailable",nil)
message:NSLocalizedString(#"Please make sure you aren't drawing an AOI or using a tool and then try again.",nil)
delegate:nil
cancelButtonTitle:NSLocalizedString(#"OK",nil) otherButtonTitles:nil] show];
}
else {
// Cancel any previous searches.
[localSearch cancel];
// Perform a new search.
MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init];
request.naturalLanguageQuery = self.searchBar.text;
request.region = self.mapView.region;
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
localSearch = [[MKLocalSearch alloc] initWithRequest:request];
[localSearch startWithCompletionHandler: ^(MKLocalSearchResponse *response, NSError *error){
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
if ([response.mapItems count] == 0)
{
[[[UIAlertView alloc] initWithTitle:NSLocalizedString(#"No Results",nil)
message:nil
delegate:nil
cancelButtonTitle:NSLocalizedString(#"OK",nil) otherButtonTitles:nil] show];
return;
}
if (error != nil)
{
[[[UIAlertView alloc] initWithTitle:NSLocalizedString(#"Map Error",nil)
message:NSLocalizedString(#"Sorry.", nil)
delegate:nil
cancelButtonTitle:NSLocalizedString(#"OK",nil) otherButtonTitles:nil] show];
return;
}
results = response;
[self.searchDisplayController.searchResultsTableView reloadData];
}
];
}
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [results.mapItems count];
}
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *IDENTIFIER = #"SearchResultsCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:IDENTIFIER];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:IDENTIFIER];
}
MKMapItem *item = results.mapItems[indexPath.row];
cell.textLabel.text = item.name;
cell.detailTextLabel.text = item.placemark.addressDictionary[#"Street"];
return cell;
}
Here is a screenshot of the issue.
The first row contains the table header.

panning cells with custom action in ios

Hi i am trying to make a tableview with mailbox style panning http://www.mailboxapp.com/ for that i am using this library https://github.com/gloubibou/HHPanningTableViewCell and it is working fine, i swipe the cell and it moves just fine, the problem is that i want to trigger a custom action when i swipe the cell and i have only been able to do it when it is open and then i touch it.
This is the code where the action is happening
#import "TableViewController.h"
#import "HHPanningTableViewCell.h"
#interface TableViewController ()
#property (nonatomic, retain) NSArray *rowTitles;
#end
#implementation TableViewController
#pragma mark -
#pragma mark Initialization
- (id)init
{
self = [super initWithNibName:#"TableViewController" bundle:nil];
if (self != nil) {
self.rowTitles = [NSArray arrayWithObjects:#"Pan direction: None", #"Pan direction: Right", #"Pan direction: Left", #"Pan direction: Both", #"Custom trigger", nil];
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// 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;
}
#pragma mark -
#pragma mark Accessors
#synthesize rowTitles = _rowTitles;
#pragma mark -
#pragma mark Rotation
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
#pragma mark -
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [self.rowTitles count] * 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
HHPanningTableViewCell *cell = (HHPanningTableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSInteger directionMask = indexPath.row % 5;
if (cell == nil) {
cell = [[HHPanningTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
UIView *drawerView = [[UIView alloc] initWithFrame:cell.frame];
// dark_dotted.png obtained from http://subtlepatterns.com/dark-dot/
// Made by Tsvetelin Nikolov http://dribbble.com/bscsystem
drawerView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"dark_dotted"]];
cell.drawerView = drawerView;
}
if (directionMask < 3) {
cell.directionMask = directionMask;
}
else {
cell.directionMask = HHPanningTableViewCellDirectionLeft + HHPanningTableViewCellDirectionRight;
if (directionMask == 4) {
cell.delegate = self;
}
}
cell.textLabel.text = [self.rowTitles objectAtIndex:directionMask];
return cell;
}
- (void)gestureRecognizerDidPan:(UIPanGestureRecognizer*)gestureRecognizer{
}
#pragma mark -
#pragma mark Table view delegate
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
NSInteger directionMask = indexPath.row;
NSString *celda = [NSString stringWithFormat:#"%d", directionMask];
[cell isKindOfClass:[HHPanningTableViewCell class]];
HHPanningTableViewCell *panningTableViewCell = (HHPanningTableViewCell*)cell;
if (directionMask == 1) {
if (HHPanningTableViewCellDirectionRight) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Custom Action"
message:#"1"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
if ([panningTableViewCell isDrawerRevealed]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Custom Action"
message:#"1"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Custom Action"
message:#"2"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
}
return indexPath;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
#pragma mark -
#pragma mark HHPanningTableViewCellDelegate
- (void)panningTableViewCellDidTrigger:(HHPanningTableViewCell *)cell inDirection:(HHPanningTableViewCellDirection)direction
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Custom Action"
message:#"You triggered a custom action"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
#end
I know i could use a Gesture recognizer to trigger the action but i think the library is already doing that.
in this part i trigger an action knowing exatly the cell, where was it paned to and if the back of the cell is revealed or not, but always by clicking it since it is a select function.
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
NSInteger directionMask = indexPath.row;
NSString *celda = [NSString stringWithFormat:#"%d", directionMask];
[cell isKindOfClass:[HHPanningTableViewCell class]];
HHPanningTableViewCell *panningTableViewCell = (HHPanningTableViewCell*)cell;
if (directionMask == 1) {
if (HHPanningTableViewCellDirectionRight) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Custom Action"
message:#"1"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
if ([panningTableViewCell isDrawerRevealed]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Custom Action"
message:#"1"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Custom Action"
message:#"2"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
}
return indexPath;
}
and i believe this other part is where the custom action should be trigered but the program never enters this function
- (void)panningTableViewCellDidTrigger:(HHPanningTableViewCell *)cell inDirection:(HHPanningTableViewCellDirection)direction
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Custom Action"
message:#"You triggered a custom action"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
I hope i made myself clear and thank you in advance.
Change the delegate method to
- (void)panningTableViewCell:(HHPanningTableViewCell *)cell didTriggerWithDirection:(HHPanningTableViewCellDirection)direction;
For the delegate method to trigger you need to set your controller as delegate for the cell. Currently in your cellForRowAtIndexPath the controller is assigned as delegate only when directionMask is 4. So you either set directionMask to be 4 in your current code (which is returning a value based on the cell position instead) or you set the controller as delegate in every case, as I've done below.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
HHPanningTableViewCell *cell = (HHPanningTableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSInteger directionMask = indexPath.row % 5;
if (cell == nil) {
cell = [[HHPanningTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
UIView *drawerView = [[UIView alloc] initWithFrame:cell.frame];
// dark_dotted.png obtained from http://subtlepatterns.com/dark-dot/
// Made by Tsvetelin Nikolov http://dribbble.com/bscsystem
drawerView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"dark_dotted"]];
cell.drawerView = drawerView;
}
if (directionMask < 3) {
cell.directionMask = directionMask;
}
else {
cell.directionMask = HHPanningTableViewCellDirectionLeft + HHPanningTableViewCellDirectionRight;
// previous code
//if (directionMask == 4) {
// cell.delegate = self;
//}
}
cell.delegate = self;
cell.textLabel.text = [self.rowTitles objectAtIndex:directionMask];
return cell;
}

Custom added cell wont save in table view

I have a alert view with a textfield so whenever someone types in it and pressed the save button it puts in the table view. when you click on the cell after being saved it takes you to a different view. Now when you go back to the home page, the cells disappear. I have tried multiple ways of figuring it out, yet still haven't been able to. Do I need to add a plist so every time I add a cell it gets saved to the plist and if so where would i start?
This code is in my table view controller
- (IBAction)add:(id)sender {
NSLog(#"%#",tableData);
UIAlertView* alert=[[UIAlertView alloc] initWithTitle:#"My Favs" message:#"Hello" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Save", nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
UITextField * alertTextField = [alert textFieldAtIndex:0];
alertTextField.enablesReturnKeyAutomatically = YES;
alertTextField.placeholder = #"example";
[alert show];
return;
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
NSLog(#"%#",tableData);
//Only do the following action if the user hits the ok button
if (buttonIndex == 1){
NSString *tapTextField = [alertView textFieldAtIndex:0].text;
if (!tableData)
{
tableData = [[NSMutableArray alloc]init];
}
[tableData insertObject:tapTextField atIndex:0];
[myTableView reloadData];
}
}
I think tableData is getting deallocated when you are coming back to the home page. If the tableData is not a huge array you can store it in NSUserDefaults. This way when ever you come back to the table you can always retreat the data. Check out this code. It will store the tableData in the NSUserDefaults every time you add anything to the array. Let me know if this works for you.
#import "ViewController.h"
#interface ViewController () <UIAlertViewDelegate,UITableViewDataSource,UITableViewDelegate>
#property (weak, nonatomic) IBOutlet UITableView *myTableView;
#property (nonatomic,strong) NSMutableArray *tableData;
#end
#implementation ViewController
-(NSMutableArray *)tableData
{
if(!_tableData){
NSMutableArray *data = [[NSUserDefaults standardUserDefaults]objectForKey:#"data"];
if(!data){
_tableData = [[NSMutableArray alloc]init];
}else{
_tableData = [data mutableCopy];
}
}
return _tableData;
}
- (IBAction)add:(UIButton *)sender {
UIAlertView* alert=[[UIAlertView alloc] initWithTitle:#"My Favs" message:#"Hello" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Save", nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
UITextField * alertTextField = [alert textFieldAtIndex:0];
alertTextField.enablesReturnKeyAutomatically = YES;
alertTextField.placeholder = #"example";
[alert show];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 1){
NSString *tapTextField = [alertView textFieldAtIndex:0].text;
[self.tableData insertObject:tapTextField atIndex:0];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:self.tableData forKey:#"data"];
[defaults synchronize];
[self.myTableView reloadData];
}
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return[self.tableData count];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"dataCell" forIndexPath:indexPath];
if(self.tableData.count > 0){
cell.textLabel.text = self.tableData[indexPath.row];
}
return cell;
}

Table View Cell/UITextField/UIControlEvent

So I was able to get the text fields to populate as subviews in my table view for the login. Now I want to reference the username text field and password text field in my login action however the action can not find the variables of the text fields (username and password) PLEASE HELP! This has been driving me nuts! Here is my code.
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *CellIdentifier = [self.menuItems objectAtIndex:indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (indexPath.row == 0) {
UITextField *username = [[UITextField alloc] init];
username.frame = CGRectMake(10, 6, 280, 30);
username.placeholder = #"Username";
cell.tag = 0;
[username addTarget:self action:#selector(login:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:username];
} else {
UITextField *password = [[UITextField alloc] init];
password.frame = CGRectMake(10, 6, 280, 30);
password.placeholder = #"Password";
cell.tag = 1;
[password addTarget:self action:#selector(login:) forControlEvents:UIControlEventTouchUpInside];
[password setSecureTextEntry:YES];
[cell.contentView addSubview:password];
}
return cell;
}
As you can see I created the text fields username and password. However the variables are not being referenced in the action! Anytime the word "username" or "password" shows up, it says "use of undeclared identifier username"/"use of undeclared identifier password". Your help will be greatly appreciated!
-(IBAction)login:(id)sender {
if ([username.text isEqualToString:#""] || [password.text isEqualToString:#""]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Oops!" message:#"Please fill in all the fields!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
return;
}
{
NSString *strURL = [NSString stringWithFormat:#"http://www.mysite.com/myfile.php?username=%#&password=%#",username.text, password.text];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
NSLog(#"%#", strResult);
NSString *cont11 = [NSString stringWithFormat:#"http://www.mysite.com/myfile.php?username=%#&password=%#",username.text, password.text];
NSData *cont12 = [NSData dataWithContentsOfURL:[NSURL URLWithString:cont11]];
NSString *cont13 = [[NSString alloc] initWithData:cont12 encoding:NSUTF8StringEncoding];
NSLog(#"%#", cont13);
if ([strResult isEqualToString:#"1"])
{
UIStoryboard *mainStoryboard=[UIStoryboard
storyboardWithName:#"Storyboard" bundle:nil];
AdminPanel *mainView=[mainStoryboard
instantiateViewControllerWithIdentifier:#"admin"];
mainView.modalTransitionStyle=UIModalTransitionStyleCoverVertical;
[self presentViewController:mainView animated:YES completion:nil];
}else
{
// invalid information
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Oops!" message:#"You must have entered something wrong! Try again!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
return;
}
}
}
You must create the variables under #interface in your .m file:
#interface YourViewController ()
{
UITextField *username;
UITextField *password;
}
Then take out "UITextField" when you init these variables.

Resources