New to iOS...i am trying to do a search with a downloaded NSMutableArray table using searchbar or do need to get search from mysql table...its driving me nuts here is code below...any help would be appreciated
#import "VendorViewController.h"
#import "VendLocation.h"
#import "VendorDetailController.h"
#interface VendorViewController ()
{
VendorModel *_VendorModel; NSMutableArray *_feedItems; VendLocation *_selectedLocation; UIRefreshControl *refreshControl;
}
#property (nonatomic, weak) IBOutlet UISearchBar *searchBar;
#end
#implementation VendorViewController
//#synthesize item;
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"Vendors";
self.searchBar.hidden = YES;
self.searchBar.delegate = self;
self.searchBar.barTintColor = [UIColor clearColor];
//self.searchBar.barTintColor = [UIColor orangeColor];
_feedItems = [[NSMutableArray alloc] init];
_VendorModel = [[VendorModel alloc] init];
_VendorModel.delegate = self;
[_VendorModel downloadItems];
#pragma mark Bar Button
UIBarButtonItem *searchItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:#selector(searchButton:)];
NSArray *actionButtonItems = #[searchItem];
self.navigationItem.rightBarButtonItems = actionButtonItems;
#pragma mark Table Refresh
UIView *refreshView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
[self.tableView insertSubview:refreshView atIndex:0]; //the tableView is a IBOutlet
refreshControl = [[UIRefreshControl alloc] init];
refreshControl.backgroundColor = [UIColor grayColor];
refreshControl.tintColor = [UIColor whiteColor];
[refreshControl addTarget:self action:#selector(reloadDatas) forControlEvents:UIControlEventValueChanged];
NSMutableAttributedString *refreshString = [[NSMutableAttributedString alloc] initWithString:#"Refreshing"];
//add date to refresh
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MMM d, h:mm a"];
NSString *lastUpdated = [NSString stringWithFormat:#"Last updated on %#", [formatter stringFromDate:[NSDate date]]];
refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:lastUpdated];
[refreshString addAttributes:#{NSForegroundColorAttributeName : [UIColor whiteColor]} range:NSMakeRange(0, refreshString.length)];
[refreshView addSubview:refreshControl];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
**#pragma mark - Search
- (void)searchButton:(id)sender{
[self.searchBar becomeFirstResponder];
self.searchBar.hidden = NO;
//[self.listTableView resignFirstResponder];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
self.searchBar.hidden = YES;
}
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
if(searchText.length == 0)
{
isFilltered = NO;
} else {
isFilltered = YES;
filteredString = [[NSMutableArray alloc]init];
for(NSString *vendorName in _feedItems)
{
NSRange vendorNameRange = [vendorName rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(vendorNameRange.location != NSNotFound) {
[filteredString addObject:vendorName];
}
}
}
[self.listTableView reloadData];
}**
#pragma mark - Table
-(void)reloadDatas {
[refreshControl endRefreshing];
}
-(void)itemsDownloaded:(NSMutableArray *)items
{ // This delegate method will get called when the items are finished downloading
_feedItems = items;
[self.listTableView reloadData];
}
#pragma mark Table Delete Button
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView
editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
return UITableViewCellEditingStyleDelete;
}
- (void) setEditing:(BOOL)editing
animated:(BOOL)animated{
[super setEditing:editing
animated:animated];
[self.listTableView setEditing:editing
animated:animated];
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
if (editingStyle == UITableViewCellEditingStyleDelete) {
[_feedItems removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:#[indexPath]
withRowAnimation:UITableViewRowAnimationLeft];
[self.tableView reloadData];
/*
NSError *error = nil;
if (![tableView save:&error]) {
NSLog(#"Can't Delete! %# %#", error, [error localizedDescription]);
return;
} */
}
}
#pragma mark TableView Delegate Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (isFilltered) {
return [filteredString count];
}
return _feedItems.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
VendLocation *item = _feedItems[indexPath.row];
static NSString *CellIdentifier = #"BasicCell";
UITableViewCell *myCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
myCell.layer.cornerRadius = 5;
myCell.layer.masksToBounds = YES;
if (myCell == nil) {
myCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; }
if (!isFilltered) {
myCell.textLabel.text = item.vendorName;
myCell.detailTextLabel.text = item.vendorNo;
//Retreive an image
UIImage *myImage = [UIImage imageNamed:#"DemoCellImage"];
[myCell.imageView setImage:myImage];
} else {
myCell.textLabel.text = [filteredString objectAtIndex:indexPath.row];
myCell.detailTextLabel.text = nil;
}
return myCell;
}
#pragma mark Tableheader
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return 55.0;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
NSString *newString = [NSString stringWithFormat:#"VENDOR \n%lu", (unsigned long) _feedItems.count];
NSString *newString1 = [NSString stringWithFormat:#"NASDAQ \n4,727.35"];
NSString *newString2 = [NSString stringWithFormat:#"DOW \n17,776.80"];
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 0)];
tableView.tableHeaderView = view; //makes header move with tablecell
[view setBackgroundColor:[UIColor clearColor]];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(12, 3, tableView.frame.size.width, 45)];
[label setFont:[UIFont systemFontOfSize:12]];
[label setTextColor:[UIColor whiteColor]];
label.numberOfLines = 0;
NSString *string = newString;
[label setText:string];
[view addSubview:label];
UIView* separatorLineView = [[UIView alloc] initWithFrame:CGRectMake(12, 45, 60, 1.5)];
separatorLineView.backgroundColor = [UIColor redColor];
[view addSubview:separatorLineView];
UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(85, 3, tableView.frame.size.width, 45)];
label1.numberOfLines = 0;
[label1 setFont:[UIFont systemFontOfSize:12]];
[label1 setTextColor:[UIColor whiteColor]];
NSString *string1 = newString1;
[label1 setText:string1];
[view addSubview:label1];
UIView* separatorLineView1 = [[UIView alloc] initWithFrame:CGRectMake(85, 45, 60, 1.5)];
separatorLineView1.backgroundColor = [UIColor redColor];
[view addSubview:separatorLineView1];
UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(158, 3, tableView.frame.size.width, 45)];
label2.numberOfLines = 0;
[label2 setFont:[UIFont systemFontOfSize:12]];
[label2 setTextColor:[UIColor whiteColor]];
NSString *string2 = newString2;
[label2 setText:string2];
[view addSubview:label2];
UIView* separatorLineView2 = [[UIView alloc] initWithFrame:CGRectMake(158, 45, 60, 1.5)];
separatorLineView2.backgroundColor = [UIColor redColor];
[view addSubview:separatorLineView2];
return view;
}
here is my header
#import <UIKit/UIKit.h>
#import "VendorModel.h"
#interface VendorViewController : UIViewController <UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, VendorModelProtocol>
{
// NSMutableArray *_feedItems;
NSMutableArray *filteredString;
BOOL isFilltered;
}
#property (weak, nonatomic) IBOutlet UITableView *listTableView;
#property (weak, nonatomic) IBOutlet UITableView *tableView;
#end
Changed Code to textDidChange
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
if(searchText.length == 0)
{
isFilltered = NO;
} else {
isFilltered = YES;
filteredString = [[NSMutableArray alloc]init];
for(VendLocation* vendor in _feedItems)
{
NSRange stringRange = [vendor.vendorName rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(stringRange.location != NSNotFound) {
[filteredString addObject:vendor];
}
}
}
[self.tableView reloadData];
}
i changed filter too this code still no luck hit a key and crash
if(searchText.length == 0)
{
isFilltered = NO;
[filteredString removeAllObjects];
[filteredString addObjectsFromArray:_feedItems];
} else {
isFilltered = YES;
// filteredString = [[NSMutableArray alloc]init];
[filteredString removeAllObjects];
for(NSString* string in _feedItems)
{
NSRange stringRange = [string rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(stringRange.location != NSNotFound) {
[filteredString addObject:string];
}
}
}
[self.tableView reloadData];
If you already have a downloaded NSMutableArray with data in it then your search can consist of merely searching through the array and filtering out entries that do not match. You do not have to go back to MySQL.
Related
I am working on chat application. Actually i have 3 arrays. First array stores user name and second array stores chat message and third array stores images. I am picking image from photo gallery.
When user sends any message to the chat wall I display message in bubble.
So I'm writing some conditions like the below:
if arr2 value is not null then displaying chat message
if arr3 value is not null displaying image in chat bubble
if arr2 value is null then i want to hide lbldesc and show only imv gallery image
if arr3 value is null then hide imv gallery image and enable lblDesc
But i got exception like this:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** NSAllocateMemoryPages(4294967295) failed'`
Here is my code:
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"cellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:nil];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
cell.selectionStyle=UITableViewCellSelectionStyleNone;
if (itemsDataArr.count>0) {
UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(35, 3, 250, 80)];
imgView.image = [UIImage imageNamed:#"speech-bubble-2-hi.png"];
imgView.layer.borderColor = [UIColor clearColor].CGColor;
imgView.tag = 5;
[cell.contentView addSubview:imgView];
NSArray *arr1=[[NSArray alloc]init];
arr1=[itemsUserNameArr objectAtIndex:indexPath.row];
NSString *strval=[arr1 objectAtIndex:0];
lblTitle=[[UILabel alloc]initWithFrame:CGRectMake(50, 5, 150, 20)];
lblTitle.highlightedTextColor=[UIColor whiteColor];
[cell.contentView addSubview:lblTitle];
[lblTitle setFont:[UIFont boldSystemFontOfSize:14]];
lblTitle.text=strval;
[imgView addSubview:lblTitle];
NSArray *arr2=[[NSArray alloc]init];
arr2=[itemsDataArr objectAtIndex:indexPath.row];
NSArray *arr3=[[NSArray alloc]init];
arr3=[itemImgArray objectAtIndex:indexPath.row];
if(![arr2 isEqual:#""])
{
NSString *strmsg=[arr2 objectAtIndex:0];
lblDesc=[[UILabel alloc]initWithFrame:CGRectMake(50, 22, 300, 20)];
lblDesc.highlightedTextColor=[UIColor whiteColor];
lblDesc.font=[UIFont systemFontOfSize:12.0];
[cell.contentView addSubview:lblDesc];
[lblDesc setHidden:NO];
lblDesc.text=strmsg;
[imgView addSubview:lblDesc];
// imv.hidden=YES;
// [imv setHidden:true];
}
arr3=[itemImgArray objectAtIndex:indexPath.row];
if(![arr3 isEqual:nil])
{
NSString *strImg=[arr3 objectAtIndex:0];
NSData *data = [[NSData alloc] initWithData:[NSData dataFromBase64String:strImg]];
//Now data is decoded. You can convert them to UIImage
imv = [[UIImageView alloc]initWithFrame:CGRectMake(93,12, 50, 50)];
imv.image=[UIImage imageWithData:data];
[imgView addSubview:imv];
[lblDesc setHidden:YES];
// lblDesc.hidden=YES;
}
}
return cell;
}
I've used PTSMessagingCell from here:
I've used messages array for texts/images. This is a ruf sample that may help you.
#import "ViewController.h"
#import "PTSMessagingCell.h"
#interface ViewController ()
{
NSMutableArray *messages;
UITextView *sendMsg;
UITableView *chatTable;
}
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
messages = [[NSMutableArray alloc] initWithObjects:#"Hello",[UIImage imageNamed:#"download.jpeg"],#"Check This Out", nil];
chatTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-100)];
chatTable.delegate = self;
chatTable.dataSource = self;
chatTable.separatorColor = [UIColor clearColor];
[self.view addSubview:chatTable];
chatTable.backgroundColor = [UIColor clearColor];
sendMsg = [[UITextView alloc]initWithFrame:CGRectMake(0, chatTable.frame.size.height, self.view.frame.size.width-100, 100)];
sendMsg.textColor = [UIColor blackColor];
sendMsg.delegate = self;
sendMsg.backgroundColor = [UIColor whiteColor];
sendMsg.layer.cornerRadius = 3.0f;
[self.view addSubview:sendMsg];
UIButton *sendMsgbtn = [[UIButton alloc]initWithFrame:CGRectMake(sendMsg.frame.size.width, chatTable.frame.size.height, 100, 100)];
[sendMsgbtn setTitle:#"SEND" forState:UIControlStateNormal];
sendMsgbtn.backgroundColor = [UIColor redColor];
[sendMsgbtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[sendMsgbtn addTarget:self action:#selector(sendClicked) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:sendMsgbtn];
UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(tapReceived:)];
[tapGestureRecognizer setDelegate:self];
[chatTable addGestureRecognizer:tapGestureRecognizer];
}
-(void)sendClicked{
[sendMsg resignFirstResponder];
[chatTable reloadData];
}
#pragma mark - TableView Delegate and DataSource Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [messages count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
/*This method sets up the table-view.*/
static NSString* cellIdentifier = #"messagingCell";
PTSMessagingCell * cell = (PTSMessagingCell*) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[PTSMessagingCell alloc] initMessagingCellWithReuseIdentifier:cellIdentifier];
}
[self configureCell:cell atIndexPath:indexPath];
return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([[messages objectAtIndex:indexPath.row] isKindOfClass:[UIImage class]]) {
return [(UIImage *)[messages objectAtIndex:indexPath.row] size].height;
}
else{
const char *jsonString = [[NSString stringWithFormat:#"%#",[messages objectAtIndex:indexPath.row]] UTF8String];
NSData *jsonData = [NSData dataWithBytes:jsonString length:strlen(jsonString)];
NSString *goodMsg = [[NSString alloc] initWithData:jsonData encoding:NSNonLossyASCIIStringEncoding];
CGSize messageSize = [PTSMessagingCell messageSize:goodMsg];
NSLog(#"%f",messageSize.height + 2*[PTSMessagingCell textMarginVertical] + 40.0f);
return messageSize.height + 2*[PTSMessagingCell textMarginVertical] + 40.0f;
}
}
-(void)configureCell:(id)cell atIndexPath:(NSIndexPath *)indexPath {
if (messages.count>0) {
PTSMessagingCell* ccell = (PTSMessagingCell*)cell;
if ([[messages objectAtIndex:indexPath.row] isKindOfClass:[UIImage class]]) {
ccell.sent = YES;
ccell.avatarImageView.image = [UIImage imageNamed:[messages objectAtIndex:indexPath.row]];
ccell.messageLabel.text = #"";
}
else{
ccell.sent = YES;
const char *jsonString = [[NSString stringWithFormat:#"%#",[messages objectAtIndex:indexPath.row]] UTF8String];
NSData *jsonData = [NSData dataWithBytes:jsonString length:strlen(jsonString)];
NSString *goodMsg = [[NSString alloc] initWithData:jsonData encoding:NSNonLossyASCIIStringEncoding];
ccell.messageLabel.text = [messages objectAtIndex:indexPath.row];
}
ccell.timeLabel.text = [NSDateFormatter localizedStringFromDate:[NSDate date] dateStyle:NSDateFormatterShortStyle timeStyle:NSDateFormatterFullStyle];
UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(tapReceived:)];
[tapGestureRecognizer setDelegate:self];
[ccell addGestureRecognizer:tapGestureRecognizer];
}
}
-(void)tapReceived:(UITapGestureRecognizer *)tapGestureRecognizer
{
// do something, like dismiss your view controller, picker, etc., etc.
[sendMsg resignFirstResponder];
}
Hope this helps.
Create a custom cell and load images in background thread will give better UI performance
I want every delete button to be tagged with its associated section's headerLabel.text.
This way, when pressing the delete button runs the deleteButtonPressed method, the deleteFromMatchCenter Parse function will use the section's headerLabel.text value as the parameter. I've tried to do it as below, but this doesn't seem to be recognizing the header title properly.
How can I properly associate each delete button with its respective sections header title, and send that over as the parameter?
MatchCenterViewController.m:
#import "MatchCenterViewController.h"
#import <UIKit/UIKit.h>
#interface MatchCenterViewController () <UITableViewDataSource, UITableViewDelegate>
#property (nonatomic, strong) UITableView *matchCenter;
#end
#implementation MatchCenterViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.matchCenter = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewCellStyleSubtitle];
self.matchCenter.frame = CGRectMake(0,50,320,self.view.frame.size.height-100);
_matchCenter.dataSource = self;
_matchCenter.delegate = self;
[self.view addSubview:self.matchCenter];
_matchCenterArray = [[NSArray alloc] init];
}
- (void)viewDidAppear:(BOOL)animated
{
self.matchCenterArray = [[NSArray alloc] init];
[PFCloud callFunctionInBackground:#"MatchCenter"
withParameters:#{
#"test": #"Hi",
}
block:^(NSArray *result, NSError *error) {
if (!error) {
_matchCenterArray = result;
[_matchCenter reloadData];
NSLog(#"Result: '%#'", result);
}
}];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return _matchCenterArray.count;
}
//the part where i setup sections and the deleting of said sections
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return 21.0f;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 21)];
headerView.backgroundColor = [UIColor lightGrayColor];
_searchTerm = [[[[_matchCenterArray objectAtIndex:section] objectForKey:#"Top 3"] objectAtIndex:3]objectForKey:#"Search Term"];
UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(8, 0, 250, 21)];
headerLabel.text = [NSString stringWithFormat:#"%#", _searchTerm];
headerLabel.font = [UIFont boldSystemFontOfSize:[UIFont systemFontSize]];
headerLabel.textColor = [UIColor whiteColor];
headerLabel.backgroundColor = [UIColor lightGrayColor];
[headerView addSubview:headerLabel];
UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
deleteButton.tag = section;
deleteButton.frame = CGRectMake(300, 2, 17, 17);
[deleteButton setImage:[UIImage imageNamed:#"xbutton.png"] forState:UIControlStateNormal];
[deleteButton addTarget:self action:#selector(deleteButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[headerView addSubview:deleteButton];
return headerView;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 3;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Initialize cell
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
// if no cell could be dequeued create a new one
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
// No cell seperators = clean design
tableView.separatorColor = [UIColor clearColor];
// title of the item
cell.textLabel.text = _matchCenterArray[indexPath.section][#"Top 3"][indexPath.row][#"Title"];
cell.textLabel.font = [UIFont boldSystemFontOfSize:14];
// price of the item
cell.detailTextLabel.text = [NSString stringWithFormat:#"$%#", _matchCenterArray[indexPath.section][#"Top 3"][indexPath.row][#"Price"]];
cell.detailTextLabel.textColor = [UIColor colorWithRed:0/255.0f green:127/255.0f blue:31/255.0f alpha:1.0f];
// image of the item
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:_matchCenterArray[indexPath.section][#"Top 3"][indexPath.row][#"Image URL"]]];
[[cell imageView] setImage:[UIImage imageWithData:imageData]];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 65;
}
- (void)deleteButtonPressed:(id)sender
{
// Define the sections title
NSString *sectionName = [self titleForHeaderInSection:indexPath.section];
// Run delete function with respective section header as parameter
[PFCloud callFunctionInBackground:#"deleteFromMatchCenter"
withParameters:
#{#"searchTerm": sectionName,}
block:^(NSDictionary *result, NSError *error) {
if (!error) {
NSLog(#"Result: '%#'", result);
[_matchCenter reloadData];
}
}];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
#end
You haven't linked your titleForHeaderInSection: method, but you're trying to pass indexPath.section when you don't have access to your indexPath.
Try this
UIButton *deleteButton = (UIButton *)sender;
NSString *sectionName = [self titleForHeaderInSection:deleteButton.tag];
or
NSString *sectionName = _searchTerm = [[[[_matchCenterArray objectAtIndex:deleteButton.tag] objectForKey:#"Top 3"] objectAtIndex:3]objectForKey:#"Search Term"];
I have a UITableViewController that I'm using for a form. Each cell has a UILabel and a UITextField. When I tap on a UITextField, the keyboard comes up, then I scroll down and the cell goes off screen, when I tap on another UITextField, the app crashes.
This is my cell subclass.
#implementation EditorFieldCell
- (id)init
{
self = [super init];
if (self) {
self.selectionStyle = UITableViewCellSelectionStyleNone;
[self.contentView addSubview:self.nameLabel];
[self.contentView addSubview:self.textField];
}
return self;
}
- (void)setName:(NSString *)name
{
_name = name;
CGRect frame = self.nameLabel.frame;
frame.size.width = roundf([_name sizeWithFont:[UIFont boldSystemFontOfSize:17.0f]].width);
self.nameLabel.frame = frame;
frame = self.textField.frame;
frame.size.width = self.frame.size.width - 16.0f - 14.0f - 14.0f - self.nameLabel.frame.size.width;
frame.origin.x = 16.0f + 14.0f + self.nameLabel.frame.size.width;
self.textField.frame = frame;
self.nameLabel.text = _name;
}
- (void)setPlaceholder:(NSString *)placeholder
{
_placeholder = placeholder;
self.textField.placeholder = placeholder;
}
- (void)setText:(NSString *)text
{
_text = text;
self.textField.text = text;
}
- (UILabel*)nameLabel
{
if (_nameLabel)
{
return _nameLabel;
}
_nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(16.0f, 0.0f, 0.0f, self.frame.size.height)];
_nameLabel.font = [UIFont boldSystemFontOfSize:17.0f];
return _nameLabel;
}
- (UITextField*)textField
{
if (_textField)
{
return _textField;
}
_textField = [[UITextField alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 0.0f, self.frame.size.height)];
_textField.font = [UIFont systemFontOfSize:17.0f];
_textField.textAlignment = NSTextAlignmentRight;
_textField.keyboardAppearance = UIKeyboardAppearanceDark;
return _textField;
}
#end
And here is my table subclass.
#interface ManageWineViewController ()
#end
#implementation ManageWineViewController
- (id)init
{
self = [super initWithStyle:UITableViewStyleGrouped];
if (self) {
self.title = #"Manage Wine";
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"Cancel" style:UIBarButtonItemStylePlain target:self action:#selector(done)];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"Save" style:UIBarButtonItemStyleDone target:self action:#selector(save)];
NSMutableArray *data = [[NSMutableArray alloc] init];
NSMutableDictionary *section = [[NSMutableDictionary alloc] init];
NSMutableArray *sectionData = [[NSMutableArray alloc] init];
[sectionData addObject:#{#"name": #"Estate", #"placeholder": #""}];
[sectionData addObject:#{#"name": #"Wine", #"placeholder": #""}];
[sectionData addObject:#{#"name": #"Vintage", #"placeholder": #"", #"keyboardType": [NSNumber numberWithInt:UIKeyboardTypeDecimalPad]}];
[section setObject:sectionData forKey:#"data"];
[data addObject:section];
section = [[NSMutableDictionary alloc] init];
sectionData = [[NSMutableArray alloc] init];
[sectionData addObject:#{#"name": #"Type"}];
[sectionData addObject:#{#"name": #"Style", #"placeholder": #"Select a Style", #"options": #[#"", #"Red", #"White", #"Rosé", #"Sparkling", #"Saké", #"Dessert, Sherry, and Port"]}];
[sectionData addObject:#{#"name": #"Appellation", #"placeholder": #""}];
[section setObject:sectionData forKey:#"data"];
[data addObject:section];
section = [[NSMutableDictionary alloc] init];
sectionData = [[NSMutableArray alloc] init];
[sectionData addObject:#{#"name": #"Alcohol %", #"placeholder": #"", #"keyboardType": [NSNumber numberWithInt:UIKeyboardTypeDecimalPad]}];
[section setObject:sectionData forKey:#"data"];
[data addObject:section];
self.data = data;
self.inputTexts = [[NSMutableDictionary alloc] initWithDictionary:#{#"0": #"",
#"1": #"",
#"2": #"",
#"10": #"",
#"11": #"",
#"12": #"",
#"20": #""}];
}
return self;
}
- (void)done
{
[self.currentTextField resignFirstResponder];
[self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
}
- (void)save
{
[self done];
}
- (void)hidePicker
{
[self.selectActionSheet dismissWithClickedButtonIndex:0 animated:YES];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return self.data.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return ((NSArray*)[[self.data objectAtIndex:section] objectForKey:#"data"]).count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *cellInfo = [((NSArray*)[[self.data objectAtIndex:indexPath.section] objectForKey:#"data"]) objectAtIndex:indexPath.row];
static NSString *CellIdentifier = #"EditorCell";
EditorFieldCell *cell = (EditorFieldCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell)
{
cell = [[EditorFieldCell alloc] init];
}
cell.textField.tag = [[NSString stringWithFormat:#"%i%i", indexPath.section, indexPath.row] integerValue];
cell.textField.delegate = self;
cell.name = cellInfo[#"name"];
cell.placeholder = cellInfo[#"placeholder"];
cell.text = [self.inputTexts objectForKey:[NSString stringWithFormat:#"%i", cell.textField.tag]];
if (cellInfo[#"keyboardType"])
{
cell.textField.keyboardType = [cellInfo[#"keyboardType"] integerValue];
}
else
{
cell.textField.keyboardType = UIKeyboardTypeDefault;
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
#pragma mark - UITextFieldDelegate methods
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
self.currentTextField = textField;
if (textField.tag == 11)
{
//show select
NSArray *options = [[[[self.data objectAtIndex:1] objectForKey:#"data"] objectAtIndex:1] objectForKey:#"options"];
self.selectTextField = textField;
self.selectOptions = options;
[textField resignFirstResponder];
self.selectActionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:nil cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
CGRect pickerFrame = CGRectMake(0, 40, 0, 0);
self.selectPickerView = [[UIPickerView alloc] initWithFrame:pickerFrame];
self.selectPickerView.showsSelectionIndicator = YES;
self.selectPickerView.dataSource = self;
self.selectPickerView.delegate = self;
[self.selectActionSheet addSubview:self.selectPickerView];
[self.selectActionSheet showInView:[[UIApplication sharedApplication] keyWindow]];
[self.selectActionSheet setBounds:CGRectMake(0, 0, 320, 485)];
}
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
[self.inputTexts setObject:textField.text forKey:[NSString stringWithFormat:#"%i", textField.tag]];
return YES;
}
#end
The error that I am getting with the crash is:
*** -[EditorFieldCell _didChangeToFirstResponder:]: message sent to deallocated instance 0x155f6e20
This is iOS 7 (and will only support iOS 7) if that helps.
You are not initialising EditorFieldCell with reuse identifier.
EditorFieldCell *cell = (EditorFieldCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
This condition will false.
if (!cell)
{
cell = [[EditorFieldCell alloc] init];
}
Try to create cell with reuseIdentifier
cell = [[EditorFieldCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
And write this in EditorFieldCell.m
-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
if (self == [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
self.selectionStyle = UITableViewCellSelectionStyleNone;
[self.contentView addSubview:self.nameLabel];
[self.contentView addSubview:self.textField];
}
}
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) {
I try to make a little program to learn more about searching a tableview about a searchbar. Meanwhile i'm in the third week trying to do this. I found many examples in different ways in the internet. The most with a searchdisplaycontroller but this way is only for a viewcontroller. i prefer a way that also works with an uiview and so i use the searchbar delegatemethod to filter my data dictionary. Normally i try as long i get handle such things by myself. But this is my nemesis. I really can't find a way to get this problem solved. Can anyone help me with my code?
Here it is.
#import "FilterDemoTableViewController.h"
#implementation FilterDemoTableViewController
#synthesize filteredTableData;
#synthesize searchBar;
#synthesize isFiltered;
#synthesize tableContents;
#synthesize Keys;
- (void)viewDidLoad
{
[super viewDidLoad];
searchBar.delegate = (id)self;
//-----------------------My TableView Data ------------------------------
NSArray *array1 = [[NSArray alloc]initWithObjects:#"Berlin",#"München",#"Stuttgart",nil];
NSArray *array2 = [[NSArray alloc]initWithObjects:#"Paris",#"Bordeaux",#"Marseille",#"Toulouse",nil];
NSArray *array3 = [[NSArray alloc]initWithObjects:#"London",#"Portsmouth",#"Oxford",#"York",#"Dover",nil];
NSArray *array4 = [[NSArray alloc]initWithObjects:#"Rom" ,#"Genua",#"Mailand",#"Florenz",nil];
NSArray *array5 = [[NSArray alloc]initWithObjects:#"Madrid",#"Barcelona",#"Toledo",#"Saragossa",#"Pamplona",nil];
NSDictionary *dictionary =[[NSDictionary alloc]initWithObjectsAndKeys:array1,#"Deutschland",array2,#"Frankreich",array3,#"Großbritannien",array4,#"Italien",array5,#"Spanien",nil];
self.tableContents = dictionary;
self.Keys = [self.tableContents allKeys];
//--------------------------------------------------------------------------
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
if (self.isFiltered) {
return [filteredTableData count];
} else {
return [Keys count];}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSArray *listData =[self.tableContents objectForKey:[self.Keys objectAtIndex:section]];
int rowCount;
if(self.isFiltered)
rowCount = filteredTableData.count;
else
rowCount = [listData count];
return rowCount;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
NSDictionary* sectionDictionary;
if (isFiltered) {
sectionDictionary = [filteredTableData objectAtIndex:indexPath.section];
} else {
sectionDictionary = [self.tableContents objectForKey:[self.Keys objectAtIndex:indexPath.section]];
}
NSArray* sectionEntries = [self.tableContents objectForKey:[self.Keys objectAtIndex:indexPath.section]];
cell.textLabel.text = [sectionEntries objectAtIndex:indexPath.row];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text
{
if(text.length == 0)
{
isFiltered = FALSE;
}
else
{
//I think here is something wrong but i don't know what
isFiltered = true;
filteredTableData = [[NSMutableArray alloc] init];
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
for (NSDictionary *dictionary in tableContents) //dictionary read
{
NSArray *array = [dictionary objectForKey:Keys]; //section of dictionary read
[searchArray addObjectsFromArray:array];
}
for (NSString *sTemp in searchArray)
{
NSRange titleResultsRange = [sTemp rangeOfString:text options:NSCaseInsensitiveSearch];
if (titleResultsRange.length != 0)
[filteredTableData addObject:sTemp];
}
}
[self.tableView reloadData];
}
- (void)viewDidUnload{
[self setSearchBar:nil];
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
Now i post a complete refreshed code. I tested each component of the code step by step. It works and the search is also fine (in a UITableViewController). But in this example the hole code is in a UIView. The reason, on this way it is possible to create non full-size tableviews and instanzes of tableviews. Much better for a clear Viewcontroller. I know that an UIView has no method like this reloadData but it is necessary.
Near the code end you can see the problem line. And for this last step i have no idea how i can solve this. [self.tableView reloadData];
#import "TableView.h"
#import <QuartzCore/QuartzCore.h>
#interface TableView ()
#end
#implementation TableView
#synthesize delegate;
#synthesize dropDownHeight;
#synthesize labelText;
#synthesize enabled;
#synthesize tableContents;
#synthesize Keys;
#synthesize searchBar;
#synthesize isFiltered;
#synthesize filteredTableData;
- (void)__show {
viewControl.alpha = 0.0f;
UIWindow *mainWindow = [[UIApplication sharedApplication] keyWindow];
[mainWindow addSubview:viewControl];
[UIView animateWithDuration:0.3f
animations:^{
viewControl.alpha = 1.0f;
}
completion:^(BOOL finished) {}];
}
- (void)__hide {
[UIView animateWithDuration:0.2f
animations:^{
viewControl.alpha = 0.0f;
}
completion:^(BOOL finished) {
[viewControl removeFromSuperview];
}];
}
- (void) setLabelText:(NSString *)_labelText{
[button setTitle:labelText forState:UIControlStateNormal];
}
- (void) setEnable:(BOOL)_enabled{
enabled = _enabled;
[button setEnabled:_enabled];
}
- (void) setArrayData:(NSArray *)_arrayData{
[table reloadData];
}
- (void) buttonPressed{
[self __show];
}
- (void) controlPressed{
//[viewControl removeFromSuperview];
[self __hide];
}
- (id) initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:CGRectMake(10, 0, 280, 30)];
[button setTitle:#"--Auswahl--" forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:#"combo_bg.png"] forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[button addTarget:self action:#selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside];
[button.titleLabel setFont:[UIFont fontWithName:#"Helvetica" size:14]];
[self addSubview:button];
dropDownHeight = 706;
viewControl = [[UIControl alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
[viewControl addTarget:self action:#selector(controlPressed) forControlEvents:UIControlEventTouchUpInside];
CGFloat x = self.frame.origin.x;
CGFloat y = (viewControl.frame.size.height - dropDownHeight)/2;
table = [[UITableView alloc] initWithFrame:CGRectMake(x, y, frame.size.width, dropDownHeight) style:UITableViewStyleGrouped];
table.dataSource = self;
table.delegate = self;
searchBar = [[UISearchBar alloc] init];
[searchBar sizeToFit];
searchBar.delegate = (id)self;
table.tableHeaderView = searchBar;
CALayer *layer = table.layer;
layer.masksToBounds = YES;
layer.cornerRadius = 2.0f;
layer.borderWidth = 1.0f;
[layer setBorderColor:[UIColor darkGrayColor].CGColor];
[viewControl addSubview:table];
CGAffineTransform rotateTable = CGAffineTransformMakeRotation(M_PI_2);
table.transform = rotateTable;
table.frame = CGRectMake(-2, -1, table.frame.size.width, table.frame.size.height);
UIImageView *tempImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"gradientBackground.png"]];
[tempImageView setFrame:self->table.frame];
table.backgroundView = tempImageView;
//----------------------- TableView Daten ------------------------------
NSArray *array1 = [[NSArray alloc]initWithObjects:#"Berlin",#"München",#"Stuttgart",#"Hamburg",nil];
NSArray *array2 = [[NSArray alloc]initWithObjects:#"Paris",#"Bordeaux",#"Marseille",#"Toulouse",nil];
NSArray *array3 = [[NSArray alloc]initWithObjects:#"London",#"Portsmouth",#"Oxford",#"York",#"Dover",nil];
NSArray *array4 = [[NSArray alloc]initWithObjects:#"Rom" ,#"Genua",#"Mailand",#"Florenz",nil];
NSArray *array5 = [[NSArray alloc]initWithObjects:#"Madrid",#"Barcelona",#"Toledo",#"Saragossa",#"Pamplona",nil];
NSDictionary *dictionary =[[NSDictionary alloc]initWithObjectsAndKeys:array1,#"Deutschland",array2,#"Frankreich",array3,#"Großbritannien",array4,#"Italien",array5,#"Spanien",nil];
self.tableContents = dictionary;
self.Keys = [self.tableContents allKeys];
// ---------------------------------------------------------------------
}
return self;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
if ([self tableView:tableView titleForHeaderInSection:section] != nil) {
return 40;
}
else {
return 0;
}
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
NSString *sectionTitle = [self tableView:tableView titleForHeaderInSection:section];
if (sectionTitle == nil) {
return nil;
}
// Create label with section title
UILabel *label = [[UILabel alloc] init];
label.frame = CGRectMake(20, 6, 300, 30);
label.backgroundColor = [UIColor clearColor];
label.textColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];
label.shadowColor = [UIColor grayColor];
label.shadowOffset = CGSizeMake(0.0, 1.0);
label.font = [UIFont boldSystemFontOfSize:16];
label.text = sectionTitle;
// Create header view and add label as a subview
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
[view addSubview:label];
return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 60.0;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection: (NSInteger)section {
return [self.Keys objectAtIndex:section];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
if (self.isFiltered)
{
return 1;
} else {
return [Keys count];}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
int rowCount;
if(self.isFiltered)
{
rowCount = [filteredTableData count];
}
else
{
NSArray *listData =[self.tableContents objectForKey:[self.Keys objectAtIndex:section]];
rowCount = [listData count];
}
return rowCount;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *SimpleTableIdentifier = #"SimpleTableIdentifier";
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier: SimpleTableIdentifier];
if(cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableIdentifier];
}
if (isFiltered)
{
NSString * stadt = [filteredTableData objectAtIndex:indexPath.row];
cell.textLabel.text = stadt;
}
else
{
NSDictionary* sectionDictionary;
sectionDictionary = [self.tableContents objectForKey:[self.Keys objectAtIndex:indexPath.section]];
NSArray* sectionEntries = [self.tableContents objectForKey:[self.Keys objectAtIndex:indexPath.section]];
cell.textLabel.text = [sectionEntries objectAtIndex:indexPath.row];
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSArray *listData =[self.tableContents objectForKey:[self.Keys objectAtIndex:[indexPath section]]];
NSUInteger row = [indexPath row];
NSString *rowValue = [listData objectAtIndex:row];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
selectedIndex = [indexPath row];
[self __hide];
[button setTitle:[[NSString alloc] initWithFormat:rowValue] forState:UIControlStateNormal];
}
- (NSInteger) selectedIndex {
return selectedIndex;
}
-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text
{
if(text.length == 0)
{
isFiltered = FALSE;
}
else
{
isFiltered = true;
[filteredTableData removeAllObjects];
for (NSString* key in self.tableContents)
{
NSArray *staedte = [self.tableContents objectForKey:key];
for (NSString *stadt in staedte)
{
NSRange titleResultsRange = [stadt rangeOfString:text options:NSCaseInsensitiveSearch];
if (titleResultsRange.length != 0)
{
[filteredTableData addObject:stadt];
}
}
}
}
[self.tableView reloadData]; //Here is the error
}
-(void)didChangeTableViewValue:(TableView *)TableView selectedIndex:(NSInteger)selectedIndex {
}
#end