how to create image in cell table view - objective-c

I want create one page in way table view. its display 4 cell that different image and name for any cell. (this information get url in loop)
first : I create one class that I can meaning 2 variable.
Recipe.h
#import
#interface Recipe : NSObject
#property (nonatomic, strong) NSString *name; // name of recipe
#property (nonatomic, strong) NSString *imageFile; // image filename of recipe
#end so now in RecipeViewController (root) I write this code :
#import "RecipeViewController.h"
#import "Recipe.h"
#interface RecipeViewController ()
{
IBOutlet UIImageView *ab;
}
#end
#implementation RecipeViewController
{
NSMutableArray *recipes;
NSInteger num;
}
#synthsize ab;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.title = #"Recipe Book";
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:#"Back" style:UIBarButtonItemStyleBordered target:nil
action:nil];
[[self navigationItem] setBackBarButtonItem:backButton];
NSString *numberbook = [[NSString alloc]initWithContentsOfURL:[NSURL
URLWithString:#"http://192.168.1.102/mamal/book.php?all"]];
NSInteger numbook = [numberbook integerValue];
NSMutableArray *b = [[NSMutableArray alloc]initWithCapacity:numbook];
for (int i = 1; i <= numbook; i++)
{
Recipe *si = [Recipe new];
NSLog(#"%d,%#",i,si);
NSString *c = [[NSString alloc]initWithContentsOfURL:[NSURL URLWithString:[NSString
stringWithFormat:#"http://192.168.1.102/mamal/book.php?info=1&b=%d",i]]];
NSString *a = [NSString stringWithFormat:#"http://192.168.1.102/mamal/book.php?p=1&b=%d",i];
[b addObject:a];
UIImage *myImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:a]]];
[ab setImage:myImage];
NSLog(#"%#",a);
NSLog(#"%#",c);
si.name = [NSString stringWithString:c];
si.imageFile =[]; //I so confused!!!
if(!recipes){
recipes = [NSMutableArray array];
}
[recipes addObject:si];
}
num = numbook;
// Remove table cell separator
[self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
// Assign our own backgroud for the view
self.parentViewController.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"common_bg"]];
self.tableView.backgroundColor = [UIColor clearColor];
// Add padding to the top of the table view
UIEdgeInsets inset = UIEdgeInsetsMake(5, 0, 0, 0);
self.tableView.contentInset = inset;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return recipes.count;
}
- (UIImage *)cellBackgroundForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSInteger rowCount = [self tableView:[self tableView] numberOfRowsInSection:0];
NSInteger rowIndex = indexPath.row;
UIImage *background = nil;
if (rowIndex == 0) {
background = [UIImage imageNamed:#"cell_top.png"];
} else if (rowIndex == rowCount - 1) {
background = [UIImage imageNamed:#"cell_bottom.png"];
} else {
background = [UIImage imageNamed:#"cell_middle.png"];
}
return background;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// Configure the cell...
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
// Display recipe in the table cell
Recipe *recipe = [recipes objectAtIndex:indexPath.row];
UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100];
recipeImageView.image = [UIImage imageNamed:recipe.imageFile];
UILabel *recipeNameLabel = (UILabel *)[cell viewWithTag:101];
recipeNameLabel.text = recipe.name;
UILabel *recipeDetailLabel = (UILabel *)[cell viewWithTag:102];
recipeDetailLabel.text = recipe.detail;
// Assign our own background image for the cell
UIImage *background = [self cellBackgroundForRowAtIndexPath:indexPath];
UIImageView *cellBackgroundView = [[UIImageView alloc] initWithImage:background];
cellBackgroundView.image = background;
cell.backgroundView = cellBackgroundView;
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
#end
I so confused and get this error :
"connection cannot have a prototype object as its destination"
also I don't know one way for display image in cell!!!

cell.imageView.image = yourImage

Try this
cell.yourImage.image = [UIImage imageNamed:#"imageName"];

Related

why there is a empty area in the upside of my UITableViewCell?

enter image description here
enter image description here
Hi guys, I need some help to solve problems
i do not know why there is an empty area in my UITableViewCell like in the picture
and when I continnue to drop up the table, the blue UITextView will disappear,then the next cell appears.Anyone know Why?
#implementation TableCellModel
+(UITableViewCell *) getCellOfFreeChampionsList
{
UITableViewCell * tableCell = [[super alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NULL];
UITextView * textView = [[UITextView alloc] init];
textView.tag = 11;
textView.text = #"1qaz2wsxE";
textView.frame = CGRectMake(5, 5, 70, 20);
textView.backgroundColor = [UIColor blueColor];
[tableCell.contentView addSubview:textView];
// UILabel * la = [[UILabel alloc] init];
// la.frame = CGRectMake(5, 50, 70, 20);
// la.tag = 12;
// [tableCell.contentView addSubview:la];
NSLog(#"%#", textView.text);
NSLog(#"count is %lu", (unsigned long)tableCell.subviews.count);
return tableCell;
}
#implementation TableViewDataSource
#synthesize tableView;
#synthesize tableCell;
#synthesize LHfetchedResultsController;
#synthesize numberOfRows;
#synthesize dataTemp;
#synthesize paused;
-(id)initWithTableView:(UITableView *) tableView
{
self = [super init];
if (self) {
self.tableView = tableView;
self.tableView.dataSource = self;
self.tableView.delegate = self;
}
return self;
}
-(void)dateSourceWithChineseNewestVideos:(NSArray *)videosResults
{
self.dataTemp = videosResults;
self.tableCell = [TableCellModel getCellOfFreeChampionsList];
self.numberOfRows = videosResults.count;
NSInteger n = self.numberOfRows;
if (self.numberOfRows == 0) {
self.numberOfRows = 1;
}
}
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// [self configCellData:indexPath cell:self.tableCell];
if (self.dataTemp.count < 0) {
NSArray * arr = self.dataTemp;
NSInteger n = arr.count;
NSInteger indexNum = indexPath.row;
ChineseNewestVideos * re1 = [self.dataTemp objectAtIndex:indexNum];
UITextView * textView = [tableCell viewWithTag:11];
textView.text = re1.title;
NSLog(#"text is %lu",(unsigned long)tableCell.subviews.count);
NSLog(#"text is %#",textView.text);
// UILabel * la = [tableCell viewWithTag:12];
// la.text = [NSString stringWithFormat:#"%lD",(long)n];
}
return self.tableCell;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// id<NSFetchedResultsSectionInfo> sectionInfo = self.LHfetchedResultsController.sections[section];
// self.numberOfRows = sectionInfo.numberOfObjects;
return self.numberOfRows;
}
Programmatically:
// Objective-C
self.automaticallyAdjustsScrollViewInsets = NO;
// Swift
self.automaticallyAdjustsScrollViewInsets = false
Using Storyboard:
because i declare UITableViewCell outside of cellForRowAtIndexPath after i move it in it works

how to create custom UICollectionViewCell

I have a UICollectionView and Im trying to set a label and an image in the collectionViewCell. Unfortunately I cant seem to get any labels to display or anything else for that matter.
Here is my code:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"cellIdentifier" forIndexPath:indexPath];
UILabel *issue = [[UILabel alloc] initWithFrame:CGRectMake(0,10,cell.bounds.size.width,40)];
if(indexPath.item %2 == 0){
cell.backgroundColor=[UIColor blueColor];
issue.text = #"Some Text";
issue.textColor = [UIColor greenColor];
issue.textAlignment = NSTextAlignmentCenter;
}
else {
cell.backgroundColor=[UIColor redColor];
issue.text = #"Some Text";
issue.textColor = [UIColor greenColor];
issue.textAlignment = NSTextAlignmentCenter;
}
}
Unfortunately no label is being displayed and neither is the text in the label.
Updated: I've added the rest of the code from this class file.
#import "ContainerListController.h"
#import "ContainerController.h"
#import "ContainerList.h"
#implementation ContainerListController
//Deallocate temp variables
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
//Initiate objects
- (id)init {
if (self = [super initWithTitle:LocStr(#"CONTAINER_LIST_TITLE") navBarHidden:NO]) {
m_paths = [ContainerList shared].paths;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(onContainerListDidChange)
name:kSDKLauncherContainerListDidChange object:nil];
}
return self;
}
//Load all the views.
- (void)loadView {
//Allocate a UI view
self.view = [[UIView alloc] init];
//Create flow layout
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
//Force Horizontal Scroll
[layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
layout.minimumInteritemSpacing =[[UIScreen mainScreen] bounds].size.width;
layout.minimumLineSpacing=0.0;
//Create Collection
UICollectionView *coll =[[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
//Allocations
m_coll = coll;
coll.dataSource =self;
coll.delegate =self;
coll.pagingEnabled = YES;
coll.collectionViewLayout = layout;
//Customize Cells
[coll registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:#"cellIdentifier"];
[coll setBackgroundColor:[UIColor orangeColor]];
[layout invalidateLayout];
//Create the subview
[self.view addSubview:coll];
//set minimum spacing
/*if(UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation)){
NSLog(#"Changed to landscape Spacing");
layout.minimumLineSpacing = 100.0f;
layout.minimumInteritemSpacing = 100.0f;
}
else{
layout.minimumLineSpacing = 40.0f;
layout.minimumInteritemSpacing = 40.0f;
}*/
//Old Layout
//UITableView *table = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
//m_table = table;
//table.dataSource = self;
//table.delegate = self;
//[self.view addSubview:table];
}
- (void)onContainerListDidChange {
m_paths = [ContainerList shared].paths;
[m_table reloadData];
[m_coll reloadData];
}
//Debugging components function
/*-(void)printComps:(NSArray* ) components{
for (NSInteger i =0; i<16; i++) {
NSString * item;
item=components[i];
}
}*/
//old tableview cell
- (UITableViewCell *)
tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:nil];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
NSString *path = [m_paths objectAtIndex:indexPath.row];
NSArray *components = path.pathComponents;
cell.textLabel.text = (components == nil || components.count == 0) ?
#"" : components.lastObject;
return cell;
}
//Old tableView
- (void)
tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSString *path = [m_paths objectAtIndex:indexPath.row];
ContainerController *c = [[ContainerController alloc] initWithPath:path];
if (c != nil) {
[self.navigationController pushViewController:c animated:YES];
}
NSLog(#"Selected an item");
}
//old TableView count for epubs
- (NSInteger)
tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section{
return m_paths.count;
}
- (void)viewDidLayoutSubviews {
//m_table.frame = self.view.bounds;
m_coll.frame = self.view.bounds;
}
//Collection View Cell Data Allocation
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
cellForItemAtIndexPath:(NSIndexPath *)indexPath{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"cellIdentifier" forIndexPath:indexPath];
UILabel *issue = [[UILabel alloc] initWithFrame:CGRectMake(0,10,cell.bounds.size.width,40)];
//UICollectionViewCell *content = [[UICollectionViewCell alloc] init];
if(indexPath.item %2 == 0){
cell.backgroundColor=[UIColor blueColor];
issue.text = #"Some Text";
issue.textColor = [UIColor greenColor];
issue.textAlignment = NSTextAlignmentCenter;
}
else {
cell.backgroundColor=[UIColor redColor];
issue.text = #"Some Text";
issue.textColor = [UIColor greenColor];
issue.textAlignment = NSTextAlignmentCenter;
}
NSString *path = [m_paths objectAtIndex:indexPath.row];
NSArray *components = path.pathComponents;
NSString *Title = components.lastObject;
NSLog(#"Title: %#",Title);
NSString *Titletest = components.lastObject;
NSInteger comp1 = components.count;
NSString *comps = #"components";
NSLog(#"There are: %ld %#", (long)comp1,comps);
NSLog(#"Title: %#",Titletest);
for (NSInteger i =0; i<15; i++) {
NSString * item;
item=components[i];
NSLog(#"Component:%ld %#",(long)i,components[i]);
}
return cell;
}
//Collection View Cell Data De-Allocation
- (void)
collectionView:(UICollectionView *)collectionView
numberofItemsInSection:(NSIndexPath *)indexPath{
[collectionView deselectItemAtIndexPath:indexPath animated:YES];
NSString *path = [m_paths objectAtIndex:indexPath.row];
ContainerController *c = [[ContainerController alloc] initWithPath:path];
if(c !=nil){
[self.navigationController pushViewController:c animated:YES];
}
}
//Collection
-(NSInteger)
collectionView:(UICollectionView *)collectionView
numberOfItemsInSection:(NSInteger)section{
return m_paths.count;
}
//Set Collection View Cell Size
-(CGSize)
collectionView:(UICollectionView *) collectionView
layout:(UICollectionViewLayout*)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
//Set Landscape size of cells
/*if(UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation)){
CGFloat cellWidth = [[UIScreen mainScreen] bounds].size.width-360;
CGFloat cellHeigt = [[UIScreen mainScreen] bounds].size.height-60;
NSLog(#"Is Landscape");
return CGSizeMake(cellWidth, cellHeigt);
}
//Set Potrait size of cells
else{
CGFloat cellWidth = [[UIScreen mainScreen] bounds].size.width-60;
CGFloat cellHeigt = [[UIScreen mainScreen] bounds].size.height-160;
NSLog(#"Is Portrait");
return CGSizeMake(cellWidth, cellHeigt);
}*/
return CGSizeMake(collectionView.bounds.size.width, collectionView.bounds.size.height);
}
//Collection View Cell Position
- (UIEdgeInsets)collectionView:
(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
if(UIDeviceOrientationIsPortrait([UIDevice currentDevice].orientation)){
return UIEdgeInsetsMake(150.0,0.0,150.0,0.0); // top, left, bottom, right
}
else{
return UIEdgeInsetsMake(20.0,0.0,0.0,0.0); // top, left, bottom, right
}
}
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation{
[m_coll performBatchUpdates:nil completion:nil];
}
-(void)viewWillTransitionToSize:withTransitionCoordinator{
[m_coll performBatchUpdates:nil completion:nil];
}
/*-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)
collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
CGFloat cellSpacing = ((UICollectionViewFlowLayout *) collectionViewLayout).minimumLineSpacing;
CGFloat cellWidth = ((UICollectionViewFlowLayout *) collectionViewLayout).itemSize.width;
NSInteger cellCount = [collectionView numberOfItemsInSection:section];
CGFloat inset = (collectionView.bounds.size.width - ((cellCount-1) * (cellWidth + cellSpacing))) * 0.5;
inset = MAX(inset, 0.0);
if(UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation)){
NSLog(#"Changed to landscape Spacing");
return inset;
}
else{
return inset;
}
}*/
#end
Clear example to use custom collectionViewCell.
Create a separate class subclass ofUICollectionViewCell see below code:
.h file:
#import <UIKit/UIKit.h>
#interface CollectionViewCell : UICollectionViewCell
#property (weak, nonatomic) IBOutlet UILabel *customLabel;
#end
.m file:
#import "CollectionViewCell.h"
#implementation CollectionViewCell
#end
Now drag and drop the collectionView inside viewController using storyboard then by selecting cell set custom class for it and connect its IBOutlet of label see below image.
Setting up custom class:
Connecting label's outlet: if adding label and other ui component from storyboard
Note: Drag uilabel inside cell before you connect its IBOutlet.
Now configure cell inside your viewController class. And configure collectionView correctly by connecting its delegate, dataSuorce and IBOutlet.
#import "ViewController.h"
#import "CollectionViewCell.h"
#interface ViewController (){
// instance variable deceleration part
NSMutableArray *yourArray;
}
#end
#implementation ViewController
- (void)viewDidLoad{
[super viewDidLoad];
_yourCollView.delegate = self;
_yourCollView.dataSource = self;
yourArray = [[NSMutableArray alloc] initWithObjects:#"1st cell",#"2nd cell",#"3rd cell",#"4th cell", nil];
// Do any additional setup after loading the view, typically from a nib.
}
// collection view delegate methods
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return [yourArray count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
CollectionViewCell *cell = (CollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:#"MyCustomCell" forIndexPath:indexPath];
// configuring cell
// cell.customLabel.text = [yourArray objectAtIndex:indexPath.row]; // comment this line if you do not want add label from storyboard
// if you need to add label and other ui component programmatically
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, cell.bounds.size.width, cell.bounds.size.height)];
label.tag = 200;
label.text = [yourArray objectAtIndex:indexPath.row];
// this adds the label inside cell
[cell.contentView addSubview:label];
return cell;
}
//Note: Above two "numberOfItemsInSection" & "cellForItemAtIndexPath" methods are required.
// this method overrides the changes you have made to inc or dec the size of cell using storyboard.
- (CGSize)collectionView:(UICollectionView *)collectionView layout: (UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
return CGSizeMake(100, 100);
}
} // class ends
Setup the cell identifier (by selecting a cell) MyCustomCell you have given inside cellForItemAtIndexPath method before use see below image:
Note: Change the text color of uilabel to white before because by default collectionView appears black.
Hope here you understand.
Create subclass of UICollectionViewCell. For instance TestCollectionViewCell.
In Storyboard drag label in cell and set "Custom class" for this UICollectionViewCell with your created class. Set Reusable identifier, if your collection view in UIViewController don't forget to set DataSource and Delegate for that collectionView.
Connect IBOutlet in your Cell subclass.
Set at least 1 value inside numberOfItemsInSection method.
Then use your subclass of cell in cellForItemAt and try set text for a label.
You are missing the:
[cell.contentView addSubview:issue];

Displaying MapView in next VC from Table view cell by taking Latitude and longitude keys from json?

I am newbie to ios...please help me in solving this.i need to display map view in next view controller by tapping the row of a table view...
Here is my json:
[{"storeId":"STORE001","name":"Creamstone","latitude":"17.441934745594924","longitude":"78.45833734609187","storeAddress":"Begumpet, OPP: HPS","storeCity":"Hyderabad"},{"storeId":"STORE002","name":"Cream Stone","latitude":"17.37732708258546","longitude":"78.49484514445066","storeAddress":"near malakpet railway station\r\nchaderghat","storeCity":"Hyderabad"}]
here is my LocationTable.m
#import "LocationTable.h"
#import "LocationViewController.h"
#import "Stores.h"
#interface LocationTable ()
{
NSDictionary *coordinates;
}
#end
#define getStores #"http://192.168.28.9:8080/FoodCart/rest/storersrc/storebycity/hyderabad"
#implementation LocationTable
#synthesize json,locations;
- (void)viewDidLoad {
[super viewDidLoad];
self.title = #"Locations";
[self.tableView reloadData];
[self retrieveData];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"LocationCell"];
Stores *location = [locations objectAtIndex:indexPath.row];
cell.textLabel.text = location.name;
cell.detailTextLabel.text = location.storeAddress;
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
LocationViewController*lvc = [[LocationViewController alloc] init];
Stores *currentlocation = [locations objectAtIndex:indexPath.row];
lvc.latitude= currentlocation.latitude;
lvc.longitude=currentlocation.longitude;
[self.navigationController pushViewController:lvc animated:YES];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return locations.count;
}
-(void)retrieveData
{
NSError*error;
NSURL * url = [NSURL URLWithString:getStores];
NSData*data = [NSData dataWithContentsOfURL:url];
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
locations = [[NSMutableArray alloc] init];
for(int i=0;i<json.count;i++)
{
NSString * cStoreId = [[json objectAtIndex:i] objectForKey:#"storeId"];
NSString * cName = [[json objectAtIndex:i] objectForKey:#"name"];
NSNumber * cLatitude = [[json objectAtIndex:i] objectForKey:#"latitude"];
NSNumber * cLongitude = [[json objectAtIndex:i] objectForKey:#"longitude"];
NSString * cStoreAddress = [[json objectAtIndex:i] objectForKey:#"storeAddress"];
Stores *mylocations = [[Stores alloc] initWithstoreId:(NSString *) cStoreId andname:(NSString *) cName andlatitude:(NSNumber *) cLatitude andlongitude:(NSNumber *) cLongitude andstoreAddress:(NSString *) cStoreAddress];
[locations addObject:mylocations];
}
}
#end
Here is my LocationViewController.m:
#import "LocationViewController.h"
#import "MapView.h"
#import "LocationTable.h"
#interface LocationViewController ()
#property (nonatomic,strong) NSNumber *latitude;
#property (nonatomic,strong) NSNumber *longitude;
#property (nonatomic,strong) IBOutlet MKMapView *Mapview;
#end
#implementation LocationViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.Mapview.delegate = self;
MapView *mapPoint = [[MapView alloc] init];
mapPoint.coordinate = CLLocationCoordinate2DMake([self.Stores.latitude doubleValue], [self.Stores.longitude doubleValue]);
// Add it to the map view
[self.Mapview addAnnotation:mapPoint];
// Zoom to a region around the pin
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(mapPoint.coordinate, 500, 500);
[self.Mapview setRegion:region];
self.title = self.Stores.name;
}
Method Declaration Of MKAnnotationView
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
MKPinAnnotationView *view = nil;
static NSString *reuseIdentifier = #"MapView";
view = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIdentifier];
if(!view) {
view = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIdentifier];
view.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
view.canShowCallout = YES;
view.animatesDrop = YES;
}
return view;
}
#end
my jsonactivity is get data from url into table View , but now I want to display that data (latitude and longitude) on map view in the next View Controller, How Could I do this ? please help me, thanks in advance !
If the LocationViewController defined in a storyboard file, then you should create him via the next method:
[[UIStoryboard storyboardWithName:<your_storyboard_name> bundle:nil] instantiateViewControllerWithIdentifier:<your_controller_identifier>];
Otherwise, all IBOutlet-objects will be a nil.

Uislider in a tableView Cell

hi everyone i'm new in iOS programming ! I have a custom table view controller with custom table view cell ! one of those cell have a uislider and a label ! I want to change label text when slider change value ! this is my code :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *cellInfo = [[self.sections objectAtIndex:currentTab] objectAtIndex:indexPath.row];
HLNotificheCell *cell = [tableView dequeueReusableCellWithIdentifier:[cellInfo objectForKey:#"cell"] forIndexPath:indexPath];
UIImageView *radioIndicator = (UIImageView *)[cell.contentView viewWithTag:200];
radioIndicator.image = (currentBullet != indexPath.row) ? [UIImage imageNamed:#"RadioOff"] : [UIImage imageNamed:#"RadioOn"];
UIImageView *av = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 80)];
av.backgroundColor = [UIColor clearColor];
av.opaque = NO;
av.image = [UIImage imageNamed:#"NewsSeparetor.png"];
cell.backgroundView = av;
cell.slider.maximumValue = 100;
cell.slider.minimumValue = 1;
cell.slider.continuous = TRUE;
//set a method which will get called when a slider in a cell changes value
[cell.slider addTarget:self action:#selector(sliderChanged:) forControlEvents:UIControlEventValueChanged];
//Keep a reference to each slider by assigning a tag so that we can determine
//which slider is being changed
cell.slider.tag = indexPath.row;
//Grab the value from the sliderValuesArray and set the slider knob to that position
return cell;
}
-(void)sliderChanged:(UISlider*)sender{
HLNotificheCell *cell = [[HLNotificheCell alloc]init];
if (sender == cell.slider) {
cell.label.text = [NSString stringWithFormat:#"%0.3f", cell.slider.value];
}
}
Actually there is a lot of bad practices in your code. Please let me explain.
Let's begin with your HLNotificheCell class. I think header file should look like this:
#import <UIKit/UIKit.h>
#define HLNotificheCellIdentifier #"HLNotificheCellIdentifier"
#interface HLNotificheCell : UITableViewCell
- (instancetype)initWithReuseIdentifier:(NSString *)reuseIdentifier;
#property (strong, nonatomic) UISlider *slider;
#property (strong, nonatomic) UIImageView *radioIndicator;
#end
and implementation file:
#import "HLNotificheCell.h"
#implementation HLNotificheCell
- (instancetype)initWithReuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
if (self) {
_slider = [[UISlider alloc] init];
_slider.maximumValue = 100;
_slider.minimumValue = 1;
_slider.continuous = YES; //YES is more natural in objc rather than TRUE.
[self addSubview: _slider];
_radioIndicator = [[UIImageView alloc] init];
[self addSubview:_radioIndicator];
UIImageView *av = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 80)];
av.backgroundColor = [UIColor clearColor];
av.opaque = NO;
av.image = [UIImage imageNamed:#"NewsSeparetor.png"];
self.backgroundView = av;
//it's better to use built-in textLabel instead of creating your own. Trust me when you will have 20 different customized cells you will get lost with their names.
self.textLabel.textColor = [UIColor redColor];
}
return self;
}
- (void)layoutSubviews {
[super layoutSubviews];
// layout your self.slider and self.radioIndicator here or use xib for it.
// e.g. this will layout slider to fit whole cell:
self.slider.frame = self.bounds;
}
#end
Ok, lets go now to cellForRowAtIndexPath method:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// try to dequeue cell if exist
HLNotificheCell *cell = (HLNotificheCell *)[tableView dequeueReusableCellWithIdentifier:HLNotificheCellIdentifier];
// if doesn't, create new one.
if (!cell) { // is enough to set slider target only once when cell is created. When reuse is not needed.
cell = [[HLNotificheCell alloc] initWithReuseIdentifier:HLNotificheCellIdentifier];
[cell.slider addTarget:self action:#selector(sliderChanged:) forControlEvents:UIControlEventValueChanged];
}
//set image as you wish:
cell.radioIndicator.image = (currentBullet != indexPath.row) ? [UIImage imageNamed:#"RadioOff"] : [UIImage imageNamed:#"RadioOn"];
//Keep a reference to each slider by assigning a tag so that we can determine
//which slider is being changed
cell.slider.tag = indexPath.row;
//Grab the value from the sliderValuesArray and set the slider knob to that position
NSNumber *sliderValue = sliderValuesArray[indexPath.row];
[cell.slider setValue:sliderValue.floatValue animated:NO]
return cell;
}
and sliderChanged: method:
-(void)sliderChanged:(UISlider*)sender{
// You cannot do this:
// HLNotificheCell *cell = [[HLNotificheCell alloc]init];
// because you have to restore reference from sender.tag as you wrote in cellForRowAtIndexPath method:
HLNotificheCell *cell = (HLNotificheCell *)[tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:slider.tag inSection:0]] // I assume you have only 1 section
cell.textLabel.text = [NSString stringWithFormat:#"%0.3f", cell.slider.value];
//save new value to the sliderValuesArray
self.sliderValuesArray[indexPath.row] = #(cell.slider.value);
}
Assumptions:
when you will use this part of code please do not use registerClass:forCellReuseIdentifier:
yours sliderValuesArray is kind of NSMutableArray class.
sliderValuesArray has been initialized with size same as number of cells, like:
self.sliderValuesArray = [[NSMutableArray alloc] initWithCapacity:<#numberOfCels#>];
for (int i = 0; i < sliderValuesArray.count; i++) {
sliderValuesArray[i] = #(0);
}
your table view contains only one type of cells (HLNotificheCell)
There could be some typos and/or lack of semicolons because I wrote it without compiler.
I doing this easier. Apple write that you can use IBActions for static rows. (You can read about it here in The Technique for Static Row Content. But I already tested it on iOS 9 with dynamic cells and it's just works :)
At first - Custom cell with IBAction
#interface SliderTableViewCell ()
#property (weak, nonatomic) IBOutlet UILabel *sliderValueLabel;
#property (weak, nonatomic) IBOutlet UISlider *slider;
#end
#implementation SliderTableViewCell
- (void)awakeFromNib {
self.slider.minimumValue = 1;
self.slider.maximumValue = 1000;
}
- (IBAction)sliderValueChanged:(id)sender {
self.sliderValueLabel.text = [NSString stringWithFormat:#"1_%.f", self.slider.value];
}
#end
Second - TableView Delegate
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
SliderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseIdentifierSliderCell];
cell.slider.value = 142;
cell.sliderValueLabel.text = #"1_142";
return cell;
}
Third - Run your app and enjoy yourself ;)

Dynamically Created Subviews within Subclassed UITableViewCell

I have a custom UITableViewCell class and would like to display images and strings linearly. For example:
Row 1: [Image1] string1 [Image2] string2 [Image3]
Row 2: [Image4] string3 [Image5]
The images have varying widths but I would like equal spacing. How would I do this? I have tried manipulating subviews and CGRectMake to no avail.
Additionally, I am using an NSDictionary to hold the content and the number of images/string is not constant for each cell.
My CustomCell class:
#import "CustomCell.h"
#implementation CustomCell
#synthesize primaryLabel,secondaryLabel,image1;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) {
// Initialization code
primaryLabel = [[UILabel alloc]init];
primaryLabel.textAlignment = UITextAlignmentLeft;
primaryLabel.font = [UIFont systemFontOfSize:16];
secondaryLabel = [[UILabel alloc]init];
secondaryLabel.textAlignment = UITextAlignmentLeft;
secondaryLabel.font = [UIFont systemFontOfSize:14];
image1 = [[UIImageView alloc]init];
[self.contentView addSubview:primaryLabel];
[self.contentView addSubview:secondaryLabel];
[self.contentView addSubview:image1];
}
return self;
}
- (void)layoutSubviews {
[super layoutSubviews];
CGRect frame;
frame= CGRectMake(0 ,5, 200, 25);
primaryLabel.frame = frame;
frame= CGRectMake(0 ,30, 200, 25);
secondaryLabel.frame = frame;
frame= CGRectMake(0, 60, 23, 20);
image1.frame = frame;
...
My RootViewController
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[CustomCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
// Set up the cell...
NSDictionary *dictionary = nil;
//Search
if (tableView == self.searchDisplayController.searchResultsTableView)
{
dictionary = [self.filteredListContent objectAtIndex:indexPath.row];
}
else
{
dictionary = [self.tableDataSource objectAtIndex:indexPath.row];
}
//Original
cell.primaryLabel.text = [dictionary objectForKey:#"Title"];
for (NSArray *keystroke in [dictionary objectForKey:#"Strokes"]) {
for (int i = 0; i < 2; i++) {
if ([(NSString *)keystroke isEqualToString:#"string1"] || [(NSString *)keystroke isEqualToString:#"string2"]) {
cell.secondaryLabel.text = (NSString *)keystroke;
}
else {
NSString *imageFilePath = [NSString stringWithFormat:#"%#.png", keystroke];
NSLog(#"%#", imageFilePath);
UIImage *myimage = [UIImage imageNamed:imageFilePath];
cell.image1.image = myimage;
}
}
}
return cell;
}
...
Obviously there are a lot of holes here. Primarily, as I loop through my dictionary, I need to move my CustomCell subview right so I can place the images/text next to the previous subview.
You are on the right track. In your UITableViewCell subclass, you will need to override layoutSubviews, define CGRects for each UIImageView or UILabel manually, and set them as the respective view's frame.
Check out CGRectGetMaxX. It will be very useful in this context.