Add UIControl programmatically - ios

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];
}

Related

UICollectionView ui label not displaying

I am new to iOS development and this is my first project that i am doing alone. i am trying to show the feed of my college's unofficial fb page using uicollectionview. I have been trying a lot of different things but nothing seems to work. The uilabel for the name is not being added to the collection view. However before i added the sizeForLabelAtIndexPath method which is to determine the size of the 2 ui labels and the height of the image to be displayed, the name label was working fine
UICollectionViewController.m file
- (void)viewDidLoad {
[super viewDidLoad];
self.title = #"DCE Speaks Up";
self.collectionView.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1];
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = NO;
NSError *error= nil;
NSURL *feedURL = [NSURL URLWithString:#"https://graph.facebook.com/382057938566656/feed?fields=id,full_picture,message,story,created_time,link&access_token=1750413825187852%7CkUl9nlZFPvdGxGZX4WYabKKG2G4"];
NSData *jsonData = [NSData dataWithContentsOfURL:feedURL];
NSDictionary *dataDictionary= [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
self.feedArray = [NSMutableArray array];
NSArray *feedTempArray = [dataDictionary objectForKey:#"data"]; //feedTempArray just used for parsing
for (NSDictionary *feedDictionary in feedTempArray) {
FacebookFeed *fbFeed =[FacebookFeed facebookFeedWithMessage:[feedDictionary objectForKey:#"message"]];
fbFeed.story = [feedDictionary objectForKey:#"story"];
fbFeed.imageURL = [NSURL URLWithString:[feedDictionary objectForKey:#"full_picture"]];
fbFeed.date = [feedDictionary objectForKey:#"created_time"];
fbFeed.sharedLink = [NSURL URLWithString:[feedDictionary objectForKey:#"link"]];
[self.feedArray addObject:fbFeed];
}
// Register cell classes
[self.collectionView registerClass:[FacebookCollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];
// Do any additional setup after loading the view.
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
FacebookCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
cell.feed = self.feedArray[indexPath.row];
cell.sizeDictionary = [self sizeForLabelAtIndexPath:indexPath.row collectionView:collectionView];
// Configure the cell
for (UIView *view in cell.contentView.subviews) {
if ([view isKindOfClass:[UILabel class]]) {
[view removeFromSuperview];
}else if ([view isKindOfClass:[UIImageView class]]){
[view removeFromSuperview];
}
}
cell.layer.shouldRasterize = YES;
cell.layer.rasterizationScale = [UIScreen mainScreen].scale;
return cell;
}
#pragma mark <UICollectionViewDelegateFlowLayout>
-(CGSize) collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
NSDictionary *sizeDictionary = [[NSDictionary alloc] init];
sizeDictionary = [self sizeForLabelAtIndexPath:indexPath.row collectionView:collectionView];
return CGSizeMake(self.view.frame.size.width - 20, [sizeDictionary[#"imageHeight"] floatValue] + [sizeDictionary[#"messageHeight"] floatValue] + [sizeDictionary[#"nameHeight"] floatValue]);
}
#pragma mark <UICollectionViewDelegate>
- (NSDictionary *) sizeForLabelAtIndexPath:(NSUInteger)indexPath collectionView:(UICollectionView *)collectionView{
FacebookFeed *feed = self.feedArray[indexPath];
CGSize nameSize = CGSizeFromString(#"DCE Speaks Up");
CGSize imageSize = CGSizeMake(0, 0);
if (feed.imageURL) {
imageSize = CGSizeMake(470, 394);
}
float height = 80;
NSString *string = #"";
if (feed.message) {
string = [feed.message stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}else if (feed.story){
string = [feed.story stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
if (string) {
NSDictionary *attributes = #{
NSFontAttributeName : [UIFont preferredFontForTextStyle:UIFontTextStyleBody]
};
CGRect bodyFrame =
[string boundingRectWithSize:CGSizeMake(CGRectGetWidth(collectionView.bounds),
CGFLOAT_MAX)
options:(NSStringDrawingUsesLineFragmentOrigin)
attributes:attributes
context:nil];
height += ceilf(CGRectGetHeight(bodyFrame));
}
return #{ #"imageHeight" : #(imageSize.height) , #"messageHeight" : #(height) , #"nameHeight" : #(nameSize.height)};
}
Custom cell file
#implementation FacebookCollectionViewCell
- (instancetype)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self)
{
self.contentView.backgroundColor = [UIColor whiteColor];
// change to our custom selected background view
self.imageView = [[UIImageView alloc] init];
self.messageLabel = [[UILabel alloc] init];
self.nameLabel = [[UILabel alloc] init];
}
return self;
}
-(void) setFeed:(FacebookFeed *)feed{
_feed = feed;
self.messageLabel.numberOfLines = 0;
self.messageLabel.lineBreakMode = 0;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *data= [NSData dataWithContentsOfURL:feed.imageURL];
UIImage *theImage=[UIImage imageWithData:data];
dispatch_async(dispatch_get_main_queue(), ^{
self.imageView.image= theImage ;
});
});
if (feed.message) {
self.messageLabel.text = [[NSString alloc] initWithString:[feed.message stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
}else{
self.messageLabel.text = [[NSString alloc] initWithString:[feed.story stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
}
self.messageLabel.font = [UIFont fontWithName:#"ArialMT" size:11];
[self.messageLabel sizeToFit];
self.nameLabel.text = #"DCE Speaks Up";
[self.nameLabel setFont:[UIFont fontWithName:#"ArialMT" size:12]];
[self.nameLabel sizeToFit];
}
-(void) layoutSubviews{
NSLog(#"%#",self.feed);
self.nameLabel.frame = CGRectMake(10, 10, self.contentView.bounds.size.width, [self.sizeDictionary[#"nameHeight"] floatValue]);
float height = 200;
if (self.contentView.bounds.size.height - [self.sizeDictionary[#"messageHeight"] floatValue] -[self.sizeDictionary[#"nameHeight"] floatValue] >100) {
height = self.contentView.bounds.size.height - [self.sizeDictionary[#"messageHeight"] floatValue] -[self.sizeDictionary[#"nameHeight"] floatValue];
}
if (self.feed.imageURL) {
self.imageView.frame = CGRectMake(10, [self.sizeDictionary[#"messageHeight"] floatValue] +[self.sizeDictionary[#"nameHeight"] floatValue], self.contentView.bounds.size.width - 20,height);
self.messageLabel.frame = CGRectMake(10, [self.sizeDictionary[#"nameHeight"] floatValue] +10, self.contentView.bounds.size.width - 10, [self.sizeDictionary[#"messageHeight"] floatValue]);
[self.contentView addSubview:self.messageLabel];
[self.contentView addSubview:self.imageView];
}else{
self.messageLabel.frame = CGRectMake(10, [self.sizeDictionary[#"nameHeight"] floatValue], self.contentView.bounds.size.width - 10, [self.sizeDictionary[#"messageHeight"] floatValue]);
[self.contentView addSubview:self.messageLabel];
}
[self.contentView addSubview:self.nameLabel];
}
#end

SearchBar and Mysql

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.

UIActivityIndicatorView Not Appearing

I am trying to show a UIActivityIndicatorView while my table view is loading data and have it disappear once loading is finished. The loading indicator never appears. What am I doing wrong?
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
#define storeURL [NSURL URLWithString: #"https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=25&playlistId=PL9DC706DCCCE00188&key=AIzaSyBS4do208_KPGHAhszfVkHadSvtfSgr7Mo"]
#import "BBYoutubeVideosTableViewController.h"
#import "Reachability.h"
#import "TSMessage.h"
#import "TSMessageView.h"
#import "YoutubeCell.h"
#import "KFBYoutubeVideoView.h"
#import "KFBAppDelegate.h"
#interface BBYoutubeVideosTableViewController ()
{
UIActivityIndicatorView *loadingIndicator;
}
#end
#implementation BBYoutubeVideosTableViewController
#synthesize title, videoID, thumbURL, descriptionString, url, titleArray, videoIDArray, thumbArray, descriptionArray;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"" style:UIBarButtonItemStylePlain target:nil action:nil];
UIImageView *backgroundImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"plain_app-background.png"]];
CGFloat width = [[UIScreen mainScreen]bounds].size.width;
CGFloat height = [[UIScreen mainScreen]bounds].size.height;
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
{
loadingIndicator = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(width / 2, height / 2, 37, 37)];
loadingIndicator.center = CGPointMake(width / 2, height / 2 - 37);
}
else
{
loadingIndicator = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(142, 365, 37, 37)];
}
loadingIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
loadingIndicator.hidesWhenStopped = YES;
Reachability *networkReachability = [Reachability reachabilityForInternetConnection];
NetworkStatus networkStatus = [networkReachability currentReachabilityStatus];
if(networkStatus == NotReachable)
{
[TSMessage showNotificationWithTitle:#"Network Error" subtitle:#"No active network connection!" type:TSMessageNotificationTypeError];
[loadingIndicator stopAnimating];
}
else {
[self.tableView addSubview:loadingIndicator];
[loadingIndicator startAnimating];
}
self.title = #"Bluegrass & Backroads";
self.tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
self.tableView.backgroundView = backgroundImage;
url = [NSURL URLWithString:#"https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=25&playlistId=PL9DC706DCCCE00188&key=AIzaSyBS4do208_KPGHAhszfVkHadSvtfSgr7Mo"];
dispatch_async(kBgQueue, ^{
NSData *data = [NSData dataWithContentsOfURL:url];
if (data == nil)
{
NSLog(#"data is nil");
}
else
{
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
}
});
}
- (void)viewDidDisappear:(BOOL)animated
{
[loadingIndicator stopAnimating];
}
- (void)fetchedData:(NSData *)responseData
{
NSError *error;
titleArray = [[NSMutableArray alloc]init];
videoIDArray = [[NSMutableArray alloc]init];
thumbArray = [[NSMutableArray alloc]init];
descriptionArray = [[NSMutableArray alloc]init];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSArray *items = [json objectForKey:#"items"];
for (NSDictionary *item in items)
{
NSDictionary *snippet = [item objectForKey:#"snippet"];
title = [snippet objectForKey:#"title"];
videoID = [[snippet objectForKey:#"resourceId"] objectForKey:#"videoId"];
thumbURL = [[[snippet objectForKey:#"thumbnails"] objectForKey:#"default"] objectForKey:#"url"];
descriptionString = [snippet objectForKey:#"description"];
[titleArray addObject:title];
[videoIDArray addObject:videoID];
UIImage *thumbnailImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:thumbURL]]];
[thumbArray addObject:thumbnailImage];
[descriptionArray addObject:descriptionString];
}
[self.tableView reloadData];
[loadingIndicator stopAnimating];
}
- (IBAction)morePressed:(id)sender
{
NSURL *kyfbVideos = [NSURL URLWithString:#"https://www.youtube.com/playlist?list=PL9DC706DCCCE00188"];
[[UIApplication sharedApplication] openURL:kyfbVideos];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [titleArray count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 215;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
return 60;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
UIColor *kfbBlue = [UIColor colorWithRed:8.0/255.0f green:77.0/255.0f blue:139.0/255.0f alpha:1];
UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, tableView.frame.size.height)];
footerView.backgroundColor = [UIColor clearColor];
CGFloat width = footerView.frame.size.width;
UIButton *moreButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
moreButton.backgroundColor = [UIColor clearColor];
[moreButton setTitle:#"More" forState:UIControlStateNormal];
[moreButton setTitleColor:kfbBlue forState:UIControlStateNormal];
moreButton.titleLabel.textAlignment = NSTextAlignmentCenter;
moreButton.titleLabel.font = [UIFont fontWithName:#"FranklinGothicStd-ExtraCond" size:25.0];
moreButton.frame = CGRectMake(width / 2 - 25, 0, 50, 50);
moreButton.layer.cornerRadius = 25.0;
moreButton.layer.borderWidth = 2.0f;
moreButton.layer.borderColor = kfbBlue.CGColor;
moreButton.clipsToBounds = YES;
moreButton.backgroundColor = [UIColor clearColor];
[moreButton addTarget:self action:#selector(morePressed:) forControlEvents:UIControlEventTouchUpInside];
[footerView addSubview:moreButton];
return footerView;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UIColor *kfbBlue = [UIColor colorWithRed:8.0/255.0f green:77.0/255.0f blue:139.0/255.0f alpha:1];
YoutubeCell *cell = [tableView dequeueReusableCellWithIdentifier:#"youtubeCell"];
if (!cell)
{
NSArray *nibs =[[NSBundle mainBundle] loadNibNamed:#"YoutubeCell" owner:self options:NULL];
cell = [nibs firstObject];
}
cell.videoTitle.text = [titleArray objectAtIndex:indexPath.row];
cell.videoDescription.text = [descriptionArray objectAtIndex:indexPath.row];
cell.videoThumbnail.image = [thumbArray objectAtIndex:indexPath.row];
cell.videoTitle.textColor = kfbBlue;
cell.videoDescription.textColor = kfbBlue;
cell.videoTitle.font = [UIFont fontWithName:#"FranklinGothicStd-ExtraCond" size:22.0];
cell.videoDescription.font = [UIFont fontWithName:#"FranklinGothicStd-ExtraCond" size:16.0];
cell.backgroundColor = [UIColor clearColor];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
{
KFBYoutubeVideoView *videoView = [[KFBYoutubeVideoView alloc]init];
videoView.videoIDString = [videoIDArray objectAtIndex:indexPath.row];
videoView.videoTitle = [titleArray objectAtIndex:indexPath.row];
videoView.videoDescription = [descriptionArray objectAtIndex:indexPath.row];
[self.navigationController pushViewController:videoView animated:YES];
}
else
{
KFBYoutubeVideoView *videoView = [[KFBYoutubeVideoView alloc]initWithNibName:nil bundle:nil];
videoView.videoIDString = [videoIDArray objectAtIndex:indexPath.row];
videoView.videoTitle = [titleArray objectAtIndex:indexPath.row];
videoView.videoDescription = [descriptionArray objectAtIndex:indexPath.row];
NSMutableArray *details = [self.splitViewController.viewControllers mutableCopy];
UINavigationController *detailNav = [[UINavigationController alloc]initWithRootViewController:videoView];
[details replaceObjectAtIndex:1 withObject:detailNav];
KFBAppDelegate *appDelegate = (KFBAppDelegate *)[[UIApplication sharedApplication]delegate];
appDelegate.splitViewController.viewControllers = details;
appDelegate.window.rootViewController = self.splitViewController;
appDelegate.splitViewController.delegate = videoView;
[appDelegate.splitViewController viewWillAppear:YES];
}
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
I figured it out. tableView was being initialized after adding loadingIndicator as a subview.

UITableView for Forms Crashes

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];
}
}

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