Dynamic UITableview with different objects - ios

I have a tableview with custom cells with UITextField, UIDatePicker, UIPickerView.
In my method cellForRowAtIndexPath I set for every row its behavior.
But I realized that when I hit the first rows at the top everything is fine, instead when I scroll down the table and change the values on the bottom for example the value I entered on line 7 is inserted on line 8 and so on in the lower lines
in practice it creates confusion with the index of the lines when I scroll the table
or for example il UITableViewCellAccessoryDisclosureIndicator instead of assigning it to line 9 when reloading the table, the table assigns it to line 2
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
UITextField *text1 = (UITextField *)[cell viewWithTag:100];
UILabel *text2 = (UILabel *)[cell viewWithTag:200];
text1.text = [valuesArray objectAtIndex:indexPath.row];
text2.text = [titlesArray objectAtIndex:indexPath.row];
switch (indexPath.row) {
case 0:
{
text1.delegate = self;
text1.tag = indexPath.row;
}
break;
case 1:
{
activityPicker = [[UIPickerView alloc] init];
activityPicker.delegate = self;
activityPicker.tag = indexPath.row;
text1.delegate = self;
text1.inputView = activityPicker;
}
break;
case 2:
{
datePicker = [[UIDatePicker alloc] init];
datePicker.datePickerMode = UIDatePickerModeDate;
[datePicker addTarget:self action:#selector(onDatePickerValueChanged:) forControlEvents:UIControlEventValueChanged];
text1.delegate = self;
text1.inputView = datePicker;
datePicker.tag = indexPath.row;
}
break;
case 3:
{
datePicker = [[UIDatePicker alloc] init];
datePicker.datePickerMode = UIDatePickerModeTime;
[datePicker addTarget:self action:#selector(onDatePickerValueChanged:) forControlEvents:UIControlEventValueChanged];
text1.delegate = self;
text1.inputView = datePicker;
datePicker.tag = indexPath.row;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm"];
[datePicker setDate: [dateFormatter dateFromString:text1.text]];
}
break;
case 4:
{
activityPicker = [[UIPickerView alloc] init];
activityPicker.delegate = self;
activityPicker.tag = indexPath.row;
NSString *km = [text1.text substringToIndex:[text1.text length]-3];
int numkm = [km intValue] - 1;
[activityPicker selectRow:numkm inComponent:0 animated:YES];
text1.delegate = self;
text1.inputView = activityPicker;
}
break;
case 5:
{
activityPicker = [[UIPickerView alloc] init];
activityPicker.delegate = self;
activityPicker.tag = indexPath.row;
text1.delegate = self;
text1.inputView = activityPicker;
}
break;
case 6:
{
activityPicker = [[UIPickerView alloc] init];
activityPicker.delegate = self;
activityPicker.tag = indexPath.row;
if ([text1.text isEqualToString:[animalsArray objectAtIndex:0]])
[activityPicker selectRow:0 inComponent:0 animated:YES];
else
[activityPicker selectRow:1 inComponent:0 animated:YES];
text1.delegate = self;
text1.inputView = activityPicker;
}
break;
case 7:
text1.delegate = self;
text1.tag = indexPath.row;
}
break;
case 8:
{
activityPicker = [[UIPickerView alloc] init];
activityPicker.delegate = self;
activityPicker.tag = indexPath.row;
if ([text1.text isEqualToString:[privacyArray objectAtIndex:0]])
[activityPicker selectRow:0 inComponent:0 animated:YES];
else
[activityPicker selectRow:1 inComponent:0 animated:YES];
text1.delegate = self;
text1.inputView = activityPicker;
}
break;
case 9:
{
text1.enabled = NO;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
break;
default:
break;
}
return cell;
}

Your problem is using the same cell identifier "Cell" for all rows. This results in cells that you have already configured for a certain row to be reloaded & reused again for another row.
Assuming you have just these 10 cell designs, you could do:
NSString* identifier = [NSString stringWithFormat: #"Cell-%d", indexPath.row];
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:identifier
forIndexPath:indexPath];
In this way, dequeueReusableCellWithIdentifier will only return the cell that was created earlier for the current indexPath.

Related

Add UIControl programmatically

I try a adding UITableView into scrollview programmatically. I have set anchors and datasource, delegate. You can see in codes. But I can't. I put a breakpoint and everything run. But I can't see in my scrollview.
UITableView *tableView = [[UITableView alloc] init];
tableView.rowHeight = 130;
tableView.translatesAutoresizingMaskIntoConstraints = false;
tableView.delegate = self;
tableView.dataSource = self;
tableView.backgroundColor = [UIColor clearColor];
[self.scrollView addSubview:tableView];
[tableView.leftAnchor constraintEqualToAnchor:self.scrollView.leftAnchor constant:8].active = YES;
[tableView.rightAnchor constraintEqualToAnchor:self.scrollView.rightAnchor constant:8].active = YES;
[tableView.topAnchor constraintEqualToAnchor:self.viewShareBasketExtra.topAnchor constant:8].active = YES;
[tableView reloadData];
This codes are working:
UILabel *lblPrice = [[UILabel alloc] init];
[lblPrice setFont:[UIFont fontWithName:#"HelveticaNeue" size:14]];
lblPrice.translatesAutoresizingMaskIntoConstraints = false;
[lblPrice setTextAlignment:NSTextAlignmentCenter];
lblPrice.text = [NSString stringWithFormat:#"%.2f TL",[_productModel Price]];
[self.priceView addSubview:lblPrice];
[lblPrice.leftAnchor constraintEqualToAnchor:self.priceView.leftAnchor constant:8].active = YES;
[lblPrice.rightAnchor constraintEqualToAnchor:self.priceView.rightAnchor constant:8].active = YES;
[lblPrice.centerXAnchor constraintEqualToAnchor:self.priceView.centerXAnchor].active = YES;
[lblPrice.centerYAnchor constraintEqualToAnchor:self.priceView.centerYAnchor].active = YES;
[self getComments];
But that codes are not working :
UITableView *tableView = [[UITableView alloc]init];
tableView.rowHeight = 130;
tableView.translatesAutoresizingMaskIntoConstraints = false;
tableView.delegate = self;
tableView.dataSource = self;
tableView.backgroundColor = [UIColor clearColor];
[self.scrollView addSubview:tableView];
[tableView.leftAnchor constraintEqualToAnchor:self.scrollView.leftAnchor constant:8].active = YES;
[tableView.rightAnchor constraintEqualToAnchor:self.scrollView.rightAnchor constant:8].active = YES;
[tableView.topAnchor constraintEqualToAnchor:self.webView.topAnchor constant:8].active = YES;
My delegate methods :
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if(commentsArray!=nil){
return [commentsArray count];
}else
{
return 0;
}
}
And I am using custom table cell:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *identity = #"CommentTableViewCell";
CommentTableViewCell *cell = (CommentTableViewCell *)[tableView dequeueReusableCellWithIdentifier:identity];
if(cell == nil){
#try {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"CommentTableViewCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
#catch (NSException *exception) {
NSLog(#"Err:%#", exception.reason);
}
#finally {
}
}
in your header file .h add the next code:
<UITableViewDelegate,UITableViewDataSource>
For example in UIVIewController Class
#interface ViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>
and this is all for you header file now got to .m and implement de nextlines:
this is for height:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{return 40.0f}
and after for this you add in your scrollview
scrollview.addSubview(yourTableView)
didLoad, now UILabel *lblPrice = [[UILabel alloc] init]; working but _webView = [[UIWebView alloc] init]; not working.
- (void)viewDidLoad {
[super viewDidLoad];
self.leftLabel = 0;
self.topLabel = 0;
self.statusWeb = 0;
[self.scrollView setBackgroundColor:[UIColor redColor]];
[lblFavoritesComment setText:[NSString stringWithFormat:#"%ld",(long)[_productModel totalFavorite]]];
[lblCommentCount setText:[NSString stringWithFormat:#"%ld",(long)[_productModel totalComments]]];
[lblProductName setText:[_productModel ProductName]];
lblDescription.lineBreakMode = UILineBreakModeWordWrap;
lblDescription.numberOfLines = 0;
[lblDescription setText:[_productModel Description]];
[lblDescription sizeToFit];
if([_productModel serviceHour] == 0){
NSString *serviceMinStr = [NSString stringWithFormat:#"%ld dk.",(long)[_productModel serviceMin]];
[lblTime setText:serviceMinStr];
}
if([_productModel serviceHour ] == 0 && [_productModel serviceMin] == 0){
[lblTime setText:#""];
}
if(![_productModel.Recipe isKindOfClass:[NSNull class]]){
if(![_productModel.Recipe isEqualToString:#"NULL"] || _productModel.Recipe.length>0){
self->statusWeb = 1;
_webView = [[UIWebView alloc] init];
_webView.translatesAutoresizingMaskIntoConstraints = false;
_webView.frame = CGRectMake(0,0,200, 300);
NSMutableString *html = [NSMutableString stringWithString: #"<html><head><title></title></head><body style=\"background:transparent;\">"];
[html appendString:[_productModel Recipe]];
[html appendString:#"</body></html>"];
[_webView setBackgroundColor:[UIColor blueColor]];
[_webView loadHTMLString:[html description] baseURL:nil];
[self.viewWebView addSubview:_webView];
[_webView.topAnchor constraintEqualToAnchor:self.viewShareBasketExtra.topAnchor constant:10].active = YES;
[_webView.rightAnchor constraintEqualToAnchor:self.view.rightAnchor constant:8].active = YES;
[_webView.leftAnchor constraintEqualToAnchor:self.view.leftAnchor constant:8].active = YES;
}
}else{
}
int multiPriceStatus = (int)[_productModel multiPrice];
if(multiPriceStatus == 1){
[self getMultiPrice];
}else{
UILabel *lblPrice = [[UILabel alloc] init];
[lblPrice setFont:[UIFont fontWithName:#"HelveticaNeue" size:14]];
lblPrice.translatesAutoresizingMaskIntoConstraints = false;
[lblPrice setTextAlignment:NSTextAlignmentCenter];
lblPrice.text = [NSString stringWithFormat:#"%.2f TL",[_productModel Price]];
[self.priceView addSubview:lblPrice];
[lblPrice.leftAnchor constraintEqualToAnchor:self.priceView.leftAnchor constant:8].active = YES;
[lblPrice.rightAnchor constraintEqualToAnchor:self.priceView.rightAnchor constant:8].active = YES;
[lblPrice.centerXAnchor constraintEqualToAnchor:self.priceView.centerXAnchor].active = YES;
[lblPrice.centerYAnchor constraintEqualToAnchor:self.priceView.centerYAnchor].active = YES;
[self getComments];
}
NSString *photo = [_productModel ProductImage];
photo = [photo stringByAddingPercentEscapesUsingEncoding : NSUTF8StringEncoding];
[imgProduct setShowActivityIndicatorView:YES];
[imgProduct setIndicatorStyle:UIActivityIndicatorViewStyleGray];
[imgProduct sd_setImageWithURL:[NSURL URLWithString:photo]
placeholderImage:[UIImage imageNamed:#"placeholder"] options:/* DISABLES CODE */ (0) == 0 ? SDWebImageRefreshCached : 0];
[imgProduct setContentMode:UIViewContentModeScaleAspectFit];
QewerFavoriteGesture *favoriteGesture = [[QewerFavoriteGesture alloc] initWithTarget:self action:#selector(addFavorite:)];
favoriteGesture.productId = [_productModel Id];
favoriteGesture.numberOfTapsRequired = 1;
[imgFavorite setUserInteractionEnabled:YES];
[imgFavorite addGestureRecognizer:favoriteGesture];
QewerFavoriteGesture *basketGesture = [[QewerFavoriteGesture alloc] initWithTarget:self action:#selector(showBasketWindow:)];
basketGesture.productId = [_productModel Id];
basketGesture.numberOfTapsRequired = 1;
[imgBasket setUserInteractionEnabled:YES];
[imgBasket addGestureRecognizer:basketGesture];
QewerFavoriteGesture *extraGesture = [[QewerFavoriteGesture alloc] initWithTarget:self action:#selector(openExtras:)];
extraGesture.productId = [_productModel Id];
extraGesture.numberOfTapsRequired = 1;
[imgExtra setUserInteractionEnabled:YES];
[imgExtra addGestureRecognizer:extraGesture];
QewerFavoriteGesture *commentGesture = [[QewerFavoriteGesture alloc] initWithTarget:self action:#selector(openComments:)];
commentGesture.productId = [_productModel Id];
commentGesture.numberOfTapsRequired = 1;
[lblCommentCount setUserInteractionEnabled:YES];
[lblCommentCount addGestureRecognizer:commentGesture];
}

iOS - Why my next view callback my previous view?

My situation is the next :
I have two view controller.
The first contains an UITableView. When I tap on a cell, the second view is called and display another UITableView.
Problem :
Immediately that my second view has been displayed, it's removed and my app come back on the first view.
In debug mode, I can see that viewDidLoad() is called and the TableView has been initialised because the TableView is filled.
But I don't know why, viewWillDisappear() is called immediately, as if the view was removed...
Could someone to help me out please?
EDIT :
My first View :
#import "CIMSaddlesResearchesSavedViewController.h"
#import <Foundation/Foundation.h>
#interface CIMSaddlesResearchesSavedViewController ()
#property (weak, nonatomic) IBOutlet UITableView *tableView;
#end
#implementation CIMSaddlesResearchesSavedViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
}
- (void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:#"NavigationBarBackground"] forBarMetrics:UIBarMetricsDefault];
}
- (void) viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
}
- (UIStatusBarStyle) preferredStatusBarStyle {
return UIStatusBarStyleLightContent;
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.researches count];
}
- (UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
static NSString *reuseIdentifier = #"researchCell";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
CIMSaddleResearch *research;
research = self.researches[indexPath.row];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"researchCell"];
}
cell.textLabel.textColor = [UIColor whiteColor];
cell.detailTextLabel.textColor = [UIColor whiteColor];
cell.backgroundColor = [UIColor clearColor];
if (research.dbId && ![research.dbId isEqual:#""]) {
CIMDbManager *dbMngr = [[CIMDbManager alloc] init];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd/MM/yyyy"];
NSMutableString *minPrice = [NSMutableString stringWithString:#""];
NSMutableString *maxPrice = [NSMutableString stringWithString:#""];
NSMutableString *currencyS = [NSMutableString stringWithString:#""];
CIMCurrency *currency = [[CIMCurrency alloc] init];;
NSMutableString *researchText = [NSMutableString stringWithString:#""];
if (research.customer && ![research.customer isEqual:#""]) {
CIMCustomer *customer = [[CIMCustomer alloc] init];
customer.dbId = research.customer;
customer = [dbMngr firstObjectFromDb:customer];
[researchText appendFormat:#"%# le %#", customer.lastName, [formatter stringFromDate:research.date]];
}
CIMSaddleResearchLine *researchLine = [[CIMSaddleResearchLine alloc] init];
researchLine.saddleResearch = research.dbId;
NSArray *lines = [dbMngr objectsFromDb:researchLine];
for(CIMSaddleResearchLine *line in lines){
if([line.field isEqualToString:#"PRIX_MIN"])
[minPrice appendFormat:#"%#", line.value];
else if([line.field isEqualToString:#"PRIX_MAX"])
[maxPrice appendFormat:#"%#", line.value];
else if([line.field isEqualToString:#"DEVISE"])
[currencyS appendFormat:#"%#", line.value];
}
if(![minPrice isEqual:#""] || ![maxPrice isEqual:#""]){
if(currencyS){
currency.dbId = currencyS;
currency = [dbMngr firstObjectFromDb:currency];
} else {
currency = [dbMngr defaultSocietyCurrency];
}
[researchText appendString:#" | Budget : "];
if(![minPrice isEqual:#""] && ![maxPrice isEqual:#""])
[researchText appendFormat:#"%#%# → %#%#", minPrice, currency.symbol, maxPrice, currency.symbol];
else if(![minPrice isEqual:#""] && [maxPrice isEqual:#""])
[researchText appendFormat:#"%#%# min.", minPrice, currency.symbol];
else if([minPrice isEqual:#""] && ![maxPrice isEqual:#""])
[researchText appendFormat:#"%#%# max.", maxPrice, currency.symbol];
}
NSMutableString *researchDetailText = [NSMutableString stringWithFormat:#"Relance le : %#", [formatter stringFromDate:research.deadline]];
CIMResearchStatus *status = [[CIMResearchStatus alloc] init];
status.dbId = research.status;
status = [dbMngr firstObjectFromDb:status];
if(status){
[researchDetailText appendFormat:#" (%#)", status.name];
}
cell.textLabel.text = researchText;
cell.detailTextLabel.text = researchDetailText;
if (research.comment && ![research.comment isEqual:#""] ) {
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
}
} else {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"saddleCell"];
cell.backgroundColor = [UIColor clearColor];
cell.textLabel.text = NSLocalizedString(#"The saddle is not in this list", nil);
cell.textLabel.textAlignment = NSTextAlignmentCenter;
}
return cell;
}
-(void) tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
CIMSaddleResearch *research = self.researches[indexPath.row];
if (research.comment && ![research.comment isEqual:#""] ) {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(#"Comment", nil)
message:research.comment
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *actionOk = [UIAlertAction actionWithTitle:NSLocalizedString(#"Ok", nil)
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action){}];
[alert addAction:actionOk];
[self presentViewController:alert animated:YES completion:nil];
}
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[self.navigationController popViewControllerAnimated:YES];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
#pragma mark - Navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"openResultResearch"]) {
UITableView *table = (UITableView*)[(UITableViewCell*)sender superview];
NSIndexPath *index = [table indexPathForCell:(UITableViewCell*) sender];
CIMSaddleResearch *research = self.researches[index.row];
CIMDbManager *dbMngr = [[CIMDbManager alloc] init];
CIMSaddleResearchLine *researchLine = [[CIMSaddleResearchLine alloc] init];
CIMSaddleResearchFormViewController *form = [[CIMSaddleResearchFormViewController alloc] init];
form.minimumPriceRow = [[XLFormRowDescriptor alloc] init];
form.maximumPriceRow = [[XLFormRowDescriptor alloc] init];
form.minimumYearRow = [[XLFormRowDescriptor alloc] init];
form.maximumYearRow = [[XLFormRowDescriptor alloc] init];
form.currency = [[CIMCurrency alloc] init];
NSMutableDictionary *filters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
[[NSMutableArray alloc] init], #"brand",
[[NSMutableArray alloc] init], #"model",
[[NSMutableArray alloc] init], #"size",
[[NSMutableArray alloc] init], #"color",
[[NSMutableArray alloc] init], #"finishing",
nil];
researchLine.saddleResearch = research.dbId;
NSArray *lines = [dbMngr objectsFromDb:researchLine];
NSSortDescriptor *sortFieldDesc = [[NSSortDescriptor alloc] initWithKey:#"field" ascending:YES selector:#selector(compare:)];
NSSortDescriptor *sortOrderDesc = [[NSSortDescriptor alloc] initWithKey:#"order" ascending:YES selector:#selector(compare:)];
lines = [lines sortedArrayUsingDescriptors:#[sortFieldDesc, sortOrderDesc]];
for(CIMSaddleResearchLine *line in lines){
if([line.field isEqualToString:#"PRIX_MIN"]){
form.minimumPriceRow.value = line.value;
}else if([line.field isEqualToString:#"PRIX_MAX"]){
form.maximumPriceRow.value = line.value;
}else if([line.field isEqualToString:#"ANNEE_MIN"]){
form.minimumYearRow.value = line.value;
}else if([line.field isEqualToString:#"ANNEE_MAX"]){
form.maximumYearRow.value = line.value;
}else if([line.field isEqualToString:#"DEVISE"]){
form.currency.dbId = line.value;
form.currency = [dbMngr firstObjectFromDb:form.currency];
}
else if([line.field isEqualToString:#"GA_REFCONSTRUC"]){
form.serialNumberRow.value = line.value;
}else if([line.field isEqualToString:#"GA_QUARTIER"]){
form.flapRow.value = line.value;
}else if([line.field isEqualToString:#"GA_MARQUE"]){
CIMBrand *brand = [[CIMBrand alloc] init];
brand.dbId = line.value;
[[filters objectForKey:#"brand"] addObject:[dbMngr firstObjectFromDb:brand]];
}else if([line.field isEqualToString:#"GA_MODEL"]){
CIMModel *model = [[CIMModel alloc] init];
model.dbId = line.value;
[[filters objectForKey:#"model"] addObject:[dbMngr firstObjectFromDb:model]];
}else if([line.field isEqualToString:#"GA_TAILLE"]){
CIMSize *size = [[CIMSize alloc] init];
size.dbId = line.value;
[[filters objectForKey:#"size"] addObject:[dbMngr firstObjectFromDb:size]];
}else if([line.field isEqualToString:#"GA_COULEUR"]){
CIMColor *color = [[CIMColor alloc] init];
color.dbId = line.value;
[[filters objectForKey:#"color"] addObject:[dbMngr firstObjectFromDb:color]];
}else if([line.field isEqualToString:#"GA_FINITION"]){
CIMFinishing *finishing = [[CIMFinishing alloc] init];
finishing.dbId = line.value;
[[filters objectForKey:#"finishing"] addObject:[dbMngr firstObjectFromDb:finishing]];
}
}
if(!form.currency.dbId && [form.currency.dbId isEqualToString:#""]){
CIMCustomer *customer = [[CIMCustomer alloc] init];
customer.dbId = research.customer;
customer = [dbMngr firstObjectFromDb:customer];
form.currency.dbId = customer.currency;
form.currency = [dbMngr firstObjectFromDb:form.currency];
}
CIMSaddlesViewController *saddlesViewController = segue.destinationViewController;
saddlesViewController.filters = filters;
saddlesViewController.saddleDbId = [NSMutableString stringWithString:#""];
saddlesViewController.selectionMode = NO;
saddlesViewController.saddleNotFoundOption = NO;
saddlesViewController.showSaddlePictures = YES;
saddlesViewController.showSaddleWarehouse = YES;
saddlesViewController.showToolbar = NO;
saddlesViewController.saddles = [dbMngr stockSaddlesWithFilters:filters
andSerialNumber:form.serialNumberRow.value
andFlap:form.flapRow.value
betweenMinimumPrice:form.minimumPriceRow.value
andMaximumPrice:form.maximumPriceRow.value
inCurrency:form.currency.dbId
betweenMinimumYear:form.minimumYearRow.value
andMaximumYear:form.maximumYearRow.value
inStock:YES];
saddlesViewController.formResearch = form;
saddlesViewController.saddlesPricesCurrency = form.currency;
}
}
#end
My second view :
#import "CIMSaddlesViewController.h"
#interface CIMSaddlesViewController ()
#property (weak, nonatomic) IBOutlet UITableView *tableView;
#end
#implementation CIMSaddlesViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
}
- (void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:#"NavigationBarBackground"] forBarMetrics:UIBarMetricsDefault];
}
- (void) viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
}
- (UIStatusBarStyle) preferredStatusBarStyle {
return UIStatusBarStyleLightContent;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.saddles count];
}
- (UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
static NSString *reuseIdentifier = #"saddleCell";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
CIMItem *saddle;
saddle = self.saddles[indexPath.row];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"saddleCell"];
}
cell.textLabel.textColor = [UIColor whiteColor];
cell.detailTextLabel.textColor = [UIColor whiteColor];
cell.backgroundColor = [UIColor clearColor];
if (saddle.dbId && ![saddle.dbId isEqual:#""]) {
NSMutableString *saddleText = [NSMutableString stringWithString:saddle.dbId];
NSMutableString *saddleDetailText = [NSMutableString stringWithString:saddle.name];
// Serial number
if (saddle.serialNumber && ![saddle.serialNumber isEqual:#""]) {
[saddleText appendFormat:#" - %#", saddle.serialNumber];
}
// Warehouse
if (self.showSaddleWarehouse) {
CIMDbManager *dbMngr = [[CIMDbManager alloc] init];
CIMStock *stock = [[CIMStock alloc] init];
stock.item = saddle.dbId;
stock.quantity = [NSNumber numberWithInt:1];
stock = [dbMngr firstObjectFromDb:stock];
if (stock) {
CIMWarehouse *warehouse = [[CIMWarehouse alloc] init];
warehouse.dbId = stock.warehouse;
warehouse = [dbMngr firstObjectFromDb:warehouse];
[saddleText appendFormat:#" → [%#]", warehouse.name];
}
}
// Estimed price
if (self.saddlesPricesCurrency) {
CIMDbManager *dbMngr = [[CIMDbManager alloc] init];
CIMSaddlePrices *saddlePrices = [[CIMSaddlePrices alloc] init];
saddlePrices.item = saddle.dbId;
saddlePrices.currency = self.saddlesPricesCurrency.dbId;
saddlePrices = [dbMngr firstObjectFromDb:saddlePrices];
if (saddlePrices) {
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setMaximumFractionDigits:0];
[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[numberFormatter setCurrencyCode:self.saddlesPricesCurrency.isoCode];
NSString *isEstimateStr;
if ([saddlePrices.isEstimate isEqual:#"-"]) {
isEstimateStr = NSLocalizedString(#"Official price", nil);
} else {
isEstimateStr = NSLocalizedString(#"Estimation", nil);
}
[saddleText appendFormat:#" | %# (%#)", [numberFormatter stringFromNumber:saddlePrices.price], isEstimateStr];
}
}
cell.textLabel.text = saddleText;
cell.detailTextLabel.text = saddleDetailText;
// Saddle pictures
if (self.showSaddlePictures && [[self.saddlesPicturesDictionary allKeys] containsObject:saddle.dbId]) {
UIButton *accessoryButton = [[UIButton alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 40.0f, 40.0f)];
if ([self.saddlesiPadPictures containsObject:saddle.dbId]) {
[accessoryButton setImage:[UIImage imageNamed:#"SaddleiPadPictureButton"] forState:UIControlStateNormal];
} else {
[accessoryButton setImage:[UIImage imageNamed:#"SaddlePictureButton"] forState:UIControlStateNormal];
}
accessoryButton.tag = indexPath.row;
[accessoryButton addTarget:self action:#selector(showSaddlePicturesViewForSaddleWithSender:) forControlEvents:UIControlEventTouchDown];
cell.accessoryView = accessoryButton;
} else {
cell.accessoryView = nil;
}
} else {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"saddleCell"];
cell.backgroundColor = [UIColor whiteColor];
cell.textLabel.text = NSLocalizedString(#"The saddle is not in this list", nil);
cell.textLabel.textAlignment = NSTextAlignmentCenter;
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (self.selectionMode) {
CIMItem *saddle = self.saddles[indexPath.row];
[self.saddleDbId setString:saddle.dbId];
[self.navigationController popViewControllerAnimated:YES];
} else {
[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}
}
#end
To be honest, this project is very big, I begun to work on it since 2 month ago and I'm alone to work on it. I didn't work in Objective-C before and even less with X-Code. I'm discovering features and Objective-C gradually...
In your first VC you call [self.navigationController popViewControllerAnimated:YES]; which tells the navigationVC to pop the currently visible view controller. If you set breakpoints to the tableview didSelectRowAtIndexPath: in first VC and to viewDidLoad in your second VC you'll see in what order they are called. I have a feeling that the order of execution could be the following:
prepare for segue in firstVC
view did load in secondVC
didSelectRowAtIndexPath in first VC
finally your second VC unloads
This is my idea without testing it. Please make sure you really need to pop the VC in didSelectRow

UIButton not select the correct cell

in my tableview I have a button in the custom cell
I used the delegates to take an action to the button
The button image changes only on the selected cell
My problem is this:
When I press the button happens:
the selected cell is working properly and the button changes correctly (correct)
the second immediately after the selected cell does not change the button (corrected)
the third cell repeats the action of the selected cell (wrong)
This is repeated endlessly do not understand why
 The button should change only the selected cell and not on other non-selected
Can you help me please?
-(void)ButtonPressedGoPoint:(FFCustomCellWithImage *)custom button:(UIButton *)gopointpressed {
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"it_IT"]];
NSNumber *likeCount = [numberFormatter numberFromString:custom.CountGoPoint.text];
if (!custom.AddGoPoint.selected) {
NSLog(#"TastoSelezionato");
likeCount = [NSNumber numberWithInt:[likeCount intValue] + 1];
custom.CountGoPoint.text = [NSString stringWithFormat:#"%#", likeCount];
[custom.AddGoPoint setBackgroundImage:[UIImage imageNamed:#"FFIMG_Medal_Blu"] forState:UIControlStateNormal];
}
else {
if ([likeCount intValue] > 0) {
likeCount = [NSNumber numberWithInt:[likeCount intValue] - 1];
custom.CountGoPoint.text = [NSString stringWithFormat:#"%#", likeCount];
}
NSLog(#"TastoDeselezionato");
[custom.AddGoPoint setBackgroundImage:[UIImage imageNamed:#"FFIMG_MedalADD"] forState:UIControlStateNormal];
}
custom.AddGoPoint.selected = !custom.AddGoPoint.selected;
}
This is my implementation of the tableview
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
self.PostDetails = [ArrayforPost objectAtIndex:indexPath.row];
static NSString *IdentificazioneCellaIMG = #"CellaIMG";
FFCustomCellWithImage * CellaIMG = (FFCustomCellWithImage * )[self.FFTableView dequeueReusableCellWithIdentifier:IdentificazioneCellaIMG];
if (CellaIMG == nil) {
CellaIMG = [[FFCustomCellWithImage alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:IdentificazioneCellaIMG ];
}
CellaIMG.delegate = self;
CellaIMG.tag = indexPath.row;
[CellaIMG.AddGoPoint setTag:indexPath.row];
if ([self AssignedGoPointToPost:self.PostDetails]) {
CellaIMG.AddGoPoint.selected =YES;
[CellaIMG.AddGoPoint setImage:[UIImage imageNamed:#"FFIMG_Medal_Blu"] forState:UIControlStateNormal];
} else {
CellaIMG.AddGoPoint.selected =NO;
[CellaIMG.AddGoPoint setImage:[UIImage imageNamed:#"FFIMG_MedalADD"] forState:UIControlStateNormal];
}
NSString *FotoPostSocial = [self.PostDetails objectForKey:FF_POST_IMMAGINE];
CellaIMG.FotoPost.file = (PFFile *)FotoPostSocial;
[CellaIMG.FotoPost loadInBackground];
CellaIMG.FotoPost.layer.masksToBounds = YES;
CellaIMG.FotoPost.layer.cornerRadius = 2.0f;
CellaIMG.FotoPost.contentMode = UIViewContentModeScaleAspectFill;
CellaIMG.backgroundCell.layer.masksToBounds = YES;
CellaIMG.backgroundCell.layer.cornerRadius = 2.0f;
CellaIMG.backgroundCell.layer.borderColor = [UIColor colorWithRed:(219/255.0) green:(219/255.0) blue:(219/255.0) alpha:(1)].CGColor;
CellaIMG.backgroundCell.layer.borderWidth = 1.0f;
CellaIMG.backgroundCell.autoresizingMask = UIViewAutoresizingFlexibleHeight;
CellaIMG.LeggiCommentoButton.layer.cornerRadius = 2.0f;
CellaIMG.FotoProfilo.layer.masksToBounds = YES;
CellaIMG.FotoProfilo.layer.cornerRadius = 25.0f;
CellaIMG.FotoProfilo.contentMode = UIViewContentModeScaleAspectFill;
CellaIMG.TestoPost.font = [UIFont fontWithName:#"Helvetica" size:14.0f];
NSString *text = [self.PostDetails objectForKey:FF_POST_TEXT];
CellaIMG.TestoPost.text = text;
[CellaIMG.TestoPost setLineBreakMode:NSLineBreakByTruncatingTail];
NSString *NomeUser = [[self.PostDetails objectForKey:FF_POST_UTENTE] objectForKey:FF_USER_NOMECOGNOME];
CellaIMG.NomeUtente.text = NomeUser;
NSString *ImmagineUtente = [[self.PostDetails objectForKey:FF_POST_UTENTE] objectForKey:FF_USER_FOTOPROFILO];
CellaIMG.FotoProfilo.file = (PFFile *)ImmagineUtente;
[CellaIMG.FotoProfilo loadInBackground];
if (CellaSelezionata == indexPath.row) {
CGFloat AltezzaLabel = [self valoreAltezzaCella: indexPath.row];
CellaIMG.TestoPost.frame = CGRectMake(CellaIMG.TestoPost.frame.origin.x, CellaIMG.TestoPost.frame.origin.y, CellaIMG.TestoPost.frame.size.width, AltezzaLabel); }
else {
CellaIMG.TestoPost.frame = CGRectMake(CellaIMG.TestoPost.frame.origin.x, CellaIMG.TestoPost.frame.origin.y, CellaIMG.TestoPost.frame.size.width, 65);
}
return CellaIMG;
}
}

How do we show a table view inside a UIAlertView

I am trying to add a UITableView inside my UIAlertView and its not showing up. I just see title & message along with "OK" button on alertview.
Below is my code and I am running on iOS 7.
- (void)showDataReceivedAlert {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Received Data" message:#"\n\n\n\n\n\n\n\n\n\n\n\n" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
UITableView *table = [[UITableView alloc]initWithFrame:CGRectMake(10, 40, 264, 120)];
table.delegate = self;
table.dataSource = self;
table.backgroundColor = [UIColor clearColor];
[alert addSubview:table];
[alert show];
}
- (NSInteger)tableView:(UITableView *)iTableView numberOfRowsInSection:(NSInteger)iSection {
return 6;
}
- (UITableViewCell *)tableView:(UITableView *)iTableView cellForRowAtIndexPath:(NSIndexPath *)iIndexPath {
static NSString *identifier = #"iBeaconDataCell";
UITableViewCell *cell = [iTableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.accessoryType = UITableViewCellAccessoryNone;
}
NSString *cellText;
NSString *cellLabelText;
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSData *encodedObject = [userDefaults objectForKey:#"data"];
MyObj *myData = (MyObj *)[NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];
switch (iIndexPath.row) {
case 0:
cellText = #"Data 1";
cellLabelText = [NSString stringWithFormat:#"%d", myData.data1];
break;
case 1:
cellText = #"Data 2";
cellLabelText = [NSString stringWithFormat:#"%d", myData.data2];
break;
case 2:
cellText = #"Data 3";
cellLabelText = [NSString stringWithFormat:#"%d", myData.data3];
break;
case 3:
cellText = #"Data 4";
cellLabelText = [NSString stringWithFormat:#"%d", myData.data4];
break;
case 4:
cellText = #"Data 5";
cellLabelText = [NSString stringWithFormat:#"%f", myData.data5];
break;
case 5:
cellText = #"Data 6";
cellLabelText = myData.data6;
break;
default:
break;
}
cell.textLabel.text = cellText;
UILabel *cellLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 150.0, 44.0)];
cellLabel.text = cellLabelText;
cell.accessoryView = cellLabel;
return cell;
}
The default alert isn't meant to take subviews. (while in ios6 and earlier add. subviews could be hacked in, this does NOT work in iOS7)
write your own custom UIView that looks and acts like an alert.
There's a lot of implementations around if you prefer not to do it yourself :) e.g. on cocoacontrols.com
From iOS 7 you need to add like this
[alertview setValue:tableView forKey:#"accessoryView"];

Unable to use searchbar to filter tableview

I am trying to filter tableview with search bar. I have written all necessary methods.
My code is as below:
What is wrong with it?? Please help me, i could not find the solution.
There should be something that I am missing
#implementation ApothekeViewController
#synthesize tableView,searchBar,mapView,eczaneler,eczanelerTemp,locationManager,searchDispController,filteredListContent,isFiltered,tableViewController;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
tableViewController = [[UITableViewController alloc] init];
tableViewController.tableView.delegate = self;
tableViewController.tableView.dataSource = self;
[tableViewController.tableView reloadData];
tableViewController.tableView.frame = CGRectMake(0,66 ,320.0, 768.0);
// tableView = [[UITableView alloc]init];
//tableView.frame = CGRectMake(0,66 ,320.0, 768.0);
//tableView.delegate = self;
//tableView.dataSource = self;
[self.view addSubview:tableViewController.tableView];
searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
searchBar.placeholder = #"Arama" ;
searchBar.delegate = self;
UISearchDisplayController *searchCon = [[UISearchDisplayController alloc]
initWithSearchBar:searchBar
contentsController:tableViewController];
self.searchDispController = searchCon;
searchDispController.delegate = self;
searchDispController.searchResultsDataSource = self;
searchDispController.searchResultsDelegate = self;
//searchBar.showsCancelButton = YES;
tableViewController.tableView.tableHeaderView = searchBar;
NSDate *now = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init ] ;
[formatter setDateFormat:#"dd MMMM yyyy, EEEE"];
[formatter setTimeZone:[NSTimeZone timeZoneWithName:#"Australia/Sydney"]];
NSString *strSelectedDate= [formatter stringFromDate:now];
UINavigationBar *naviBarObj = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 1024, 55)];
UILabel *date = [[UILabel alloc] initWithFrame:CGRectMake(760,25,400,30)];
date.text = strSelectedDate;
date.textColor = [UIColor whiteColor];
[date setFont:[UIFont fontWithName:#"Arial" size:25]];
[naviBarObj addSubview:date];
[date setBackgroundColor:[UIColor clearColor]];
naviBarObj.topItem.titleView = date;
UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(60,5,400,50)];
title.text = #"En Yakın Eczane";
title.textColor = [UIColor whiteColor];
[title setFont:[UIFont fontWithName:#"Arial" size:40]];
[naviBarObj addSubview:title];
[title setBackgroundColor:[UIColor clearColor]];
naviBarObj.topItem.titleView = title;
UIBarButtonItem *btnCancel = [[UIBarButtonItem alloc]
initWithTitle:#"Cancel"
style:UIBarButtonItemStyleBordered
target:self
action:#selector(cancel_Clicked:)];
naviBarObj.topItem.leftBarButtonItem = btnCancel;
[self.view addSubview:naviBarObj];
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
mapView = [[MKMapView alloc] initWithFrame:CGRectMake(320, 66, 704, 705)];
mapView.delegate = self;
[self.view addSubview:mapView];
mapView.showsUserLocation = YES;
eczanelerTemp = [[NSMutableArray alloc]init];
self.eczaneler = [[NSMutableArray alloc] init];
Eczane *eczane1 = [[Eczane alloc] init];
eczane1.customerName = #"Duyarlı Eczanesi";
eczane1.customerID = #"mohammed#gmail.com";
eczane1.longitude = #"29.0312";
eczane1.latitude = #"41.109817";
Eczane *eczane2 = [[Eczane alloc] init];
eczane2.customerName = #"Azim Eczanesi Azim";
eczane2.customerID = #"azim#gmail.com";
eczane2.longitude = #"30.0312";
eczane2.latitude = #"41.109817";
[self.eczaneler addObject:eczane1];
[self.eczaneler addObject:eczane2];
Eczane *eczane3 = [[Eczane alloc] init];
eczane3.customerName = #"Optik Eczanesi";
eczane3.customerID = #"optik#gmail.com";
eczane3.longitude = #"29.0352";
eczane3.latitude = #"40.109817";
[self.eczaneler addObject:eczane3];
for(int i=0; i<[eczaneler count];i++)
{
Eczane *temp = [self.eczaneler objectAtIndex:i];
CLLocationCoordinate2D coordinate;
coordinate.longitude = [temp.longitude floatValue];
coordinate.latitude = [temp.latitude floatValue];
CustomAnnotation *point = [[CustomAnnotation alloc] init];
point.coordinate = coordinate;
[self.mapView addAnnotation:point];
}
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.mapView.delegate = self;
[self.mapView setShowsUserLocation:YES];
return YES;
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView2 viewForAnnotation:(id <MKAnnotation>)annotation
{
if ([annotation isKindOfClass:[MKUserLocation class]])
{
return nil;
}
else if ([annotation isKindOfClass:[CustomAnnotation class]])
{
static NSString * const identifier = #"MyCustomAnnotation";
MKAnnotationView* annotationView = [mapView2 dequeueReusableAnnotationViewWithIdentifier:identifier];
if (annotationView)
{
annotationView.annotation = annotation;
}
else
{
annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation
reuseIdentifier:identifier];
}
// set annotationView properties
UIImageView * ecz = [[UIImageView alloc]init];
ecz.frame = CGRectMake(0, 0, 65, 49);
ecz.image = [UIImage imageNamed:#"indicator.png"];
UIImageView * vstd = [[UIImageView alloc]init];
vstd.frame = CGRectMake(33, 10, 24, 22);
vstd.image = [UIImage imageNamed:#"indicator_ziyaret_gri"];
UIImageView * nbox = [[UIImageView alloc]init];
nbox.frame = CGRectMake(48, -6, 22, 22);
nbox.image = [UIImage imageNamed:#"numara_kutusu"];
[annotationView addSubview:ecz];
[annotationView addSubview:vstd];
UILabel *index = [[UILabel alloc] initWithFrame:CGRectMake(5,4,15,15)];
// index.text =[NSString stringWithFormat:#"%d", iterator ];
index.textColor = [UIColor whiteColor];
[index setFont:[UIFont fontWithName:#"Arial-BoldMT" size:18]];
[nbox addSubview:index];
[index setBackgroundColor:[UIColor clearColor]];
[annotationView addSubview:nbox];
//annotationView. = [UIImage imageNamed:#"indicator.png"];
annotationView.canShowCallout = YES;
return annotationView;
}
return nil;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (self.tableViewController.tableView == self.searchDisplayController.searchResultsTableView) {
return [filteredListContent count];
} else {
return [eczaneler count];
}
}
-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 110;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"cellForRowAtIndexPath");
static NSString *CellIdentifier = #"EczaneCell";
EczaneCell *cell = (EczaneCell *) [self.tableViewController.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[EczaneCell alloc] initWithFrame:CGRectZero] autorelease];
}
Eczane *eczane = [[Eczane alloc]init];
if (self.tableViewController.tableView == self.searchDisplayController.searchResultsTableView) {
eczane = [self.filteredListContent objectAtIndex:[indexPath row]];
} else {
eczane = [self.eczaneler objectAtIndex:[indexPath row]];
}
cell.circleIndex.text = [NSString stringWithFormat:#"%d", ([indexPath row]+1)];
cell.cellName.text = eczane.customerName;
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//EczaneCell *cell = [tableView cellForRowAtIndexPath:indexPath];
Eczane *eczane = [self.eczaneler objectAtIndex:[indexPath row]];
CLLocationCoordinate2D coordinate;
coordinate.longitude = [eczane.longitude floatValue];
coordinate.latitude = [eczane.latitude floatValue];
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(coordinate, 2000, 2000);
[mapView setRegion:region animated:YES];
}
#pragma mark -
#pragma mark UISearchDisplayController Delegate Methods
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[filteredListContent removeAllObjects];
for (Eczane *eczObj in eczaneler)
{
NSComparisonResult result = [eczObj.customerName compare:searchString options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchString length])];
if (result == NSOrderedSame)
{
[self.filteredListContent addObject:eczObj];
}
}
[self.searchDispController.searchResultsTableView reloadData];
//[self.tableViewController.tableView reloadData];
//[self.tableViewController.tableView] = [self.searchDispController.searchResultsTableView ];
[self.tableViewController.tableView reloadData];
[searchDispController.searchResultsTableView setFrame:CGRectMake(0, 44, 320, [filteredListContent count]*(searchDispController.searchResultsTableView.rowHeight))];
return YES;
}
#end
Your problem is probably:
contentsController:tableViewController
Because you have 'stolen' the table view from the controller and made yourself the delegate and data source so the search controller will be trying to gather source information using a broken controller.
Make self the contents controller.
Your next problem is:
if (self.tableViewController.tableView == self.searchDisplayController.searchResultsTableView) {
Again, because you broke that controller (you should fix that, why are you creating a table view controller and then stealing its view?). Change it to:
if (tableView == self.searchDisplayController.searchResultsTableView) {

Resources