longpress custom items UICollectionViewCell image change - uiimageview

How can I make a cell imageview to change after longpress gesture?
With this one when I click on a cell (longpress) the 4 customized items appear but when I select one of them the app crashes. (if you remove :(Cell*)cell and cell.imageView.image = [UIImage imageNamed:[NSString stringWithFormat:#"ICUbedRED.png"]]; it works...I mean the alertView appears but of course the image doesn't change).
- (void)longPress:(UILongPressGestureRecognizer *)recognizer {
if (recognizer.state == UIGestureRecognizerStateBegan) {
Cell *cell = (Cell *)recognizer.view;
[cell becomeFirstResponder];
UIMenuItem *highDep = [[UIMenuItem alloc] initWithTitle:#"High Dependency" action:#selector(hiDep:)];
UIMenuItem *lowDep = [[UIMenuItem alloc] initWithTitle:#"Low Dependency" action:#selector(lowDep:)];
UIMenuItem *booked = [[UIMenuItem alloc] initWithTitle:#"Booked" action:#selector(booked:)];
UIMenuItem *free = [[UIMenuItem alloc] initWithTitle:#"Free" action:#selector(free:)];
UIMenuController *menu = [UIMenuController sharedMenuController];
[menu setMenuItems:[NSArray arrayWithObjects:booked, highDep, lowDep, free, nil]];
[menu setTargetRect:cell.frame inView:cell.superview];
[menu setMenuVisible:YES animated:YES];
}
}
the voids are:
- (void)hiDep:(Cell*)cell
{
NSLog(#"Bed is HiDep");
cell.imageView.image = [UIImage imageNamed:[NSString stringWithFormat:#"ICUbedRED.png"]];
UIAlertView *testAlert = [[UIAlertView alloc] initWithTitle:#"This Bed is High Dependency"
message:#""
delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[testAlert show];
[testAlert release];
}
- (void)lowDep:(Cell*)cell
{.
cell.imageView.image = [UIImage imageNamed:[NSString stringWithFormat:#"ICUbedYELLOW.png"]];
..}
- (void)free:(Cell*)cell
{..
cell.imageView.image = [UIImage imageNamed:[NSString stringWithFormat:#"ICUbedGREEN.png"]];
.}
- (void)booked:(Cell*)cell
{..
cell.imageView.image = [UIImage imageNamed:[NSString stringWithFormat:#"ICUbedBLUE.png"]];
.}
and the cell building method is:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identifier = #"Cell";
Cell *cvc = (Cell *)[collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
int i = indexPath.row%[labelArray count];
number = i;
UILongPressGestureRecognizer *recognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:#selector(longPress:)];
[cvc addGestureRecognizer:recognizer];
cvc.imageView.image = [UIImage imageNamed:[NSString stringWithFormat:#"icubed.png"]];
cvc.label.text = [labelArray objectAtIndex:number];
return cvc;
}

#dottorfeelgood It is crashing for
cell.imageView.image = [UIImage imageNamed:[NSString stringWi......
because, the object retured as param to methods like
(void)lowDep:(Cell*)cell
is not of Class Cell, the retured param is of class UIMenuItem. because you are clicking on menuItems not Cell.
Instead of doing what you are doing now, you can use the MenuItems and corresponding actions on UICollectionCell solution provided by UICollectionView by default. You can check this tutorial here!
Just implement the 3 delegate methods and
// These methods provide support for copy/paste actions on cells.
// All three should be implemented if any are.
- (BOOL)collectionView:(UICollectionView *)collectionView shouldShowMenuForItemAtIndexPath:(NSIndexPath *)indexPath;
- (BOOL)collectionView:(UICollectionView *)collectionView canPerformAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender;
- (void)collectionView:(UICollectionView *)collectionView performAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender;
and set your custom menuItems needed to the sharedMenuController in ViewdidLoad.
Hope this helps, excuse my bad sentence forming.

Related

UICollectionView adding image and button

I used UICollectionView for displaying the images from CameraRoll, it is working fine, now I want to add the Camera button in the collectionview cell. I had written the code like this, button is not getting displayed.
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"collectionCell" forIndexPath:indexPath];
[self.cameraRoll thumbAtIndex:indexPath.row completionHandler:^(UIImage *thumb) {
UIImageView *imageView = [[UIImageView alloc] initWithImage:thumb];
imageView.frame = CGRectMake(0,0,cell.frame.size.width, cell.frame.size.height);
imageView.contentMode = UIViewContentModeScaleAspectFill;
[cell.contentView addSubview:imageView];
//Now Create Button
UIImage* img = [UIImage imageNamed:#"btn_take_pic"];
UIImageView *btnImage = [[UIImageView alloc] initWithImage:img];
btnImage.frame = CGRectMake(0,0, 50,50);
btnImage.frame = CGRectMake(0,0,cell.frame.size.width, cell.frame.size.height);
btnImage.contentMode = UIViewContentModeScaleAspectFill;
//End of create button
[cell.contentView addSubview:btnImage];//Add Button to the cell
}];
return cell;
}
Create Button like this
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"collectionCell" forIndexPath:indexPath];
//Add your image showing code here
//Now Create Button in cell
CGRect btnRect = CGRectMake(0, 0 , 30 , 30);
UIButton *cellBtn = [[UIButton alloc] initWithFrame:btnRect];
[cellBtn setBackgroundImage:[UIImage imageNamed:#"img.png"] forState:UIControlStateNormal];
[cellBtn setTitle:#"Text to Show" forState:UIControlStateNormal];
[cell.contentView addSubview:cellBtn];
[[cell cellBtn] addTarget:self action:#selector(CellBtnTapped:event:) forControlEvents:UIControlEventTouchUpInside];
return cell;
}
method for button tap
-(void)CellBtnTapped:(id)sender event:(id)event
{
// perform your action here that you want to do on button tap
}
But It is good that you should make a separate class for your CollectionViewCell and add all objects there, that you want to take in your collectionView cell.
This is the solution for the issue I mentioned above, I think it might be helpful for others, so positing the code here
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"collectionCell" forIndexPath:indexPath];
if(indexPath.row>0)
[self.cameraRoll thumbAtIndex:(indexPath.row-1) completionHandler:^(UIImage *thumb) {
UIImageView *imageView = [[UIImageView alloc] initWithImage:thumb];
imageView.frame = CGRectMake(0,0,cell.frame.size.width, cell.frame.size.height);
imageView.contentMode = UIViewContentModeScaleAspectFill;
[cell.contentView addSubview:imageView];
}];
else{
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"btn_take_pic.png"]];
imageView.frame = CGRectMake(0,0,cell.frame.size.width, cell.frame.size.height);
imageView.contentMode = UIViewContentModeScaleAspectFill;
[cell.contentView addSubview:imageView];
}
return cell;
}

Loading Images into a tableview cell, according to object loaded from NSUserDefaults

I have a tableview populated by objects loaded from NSUserDefaults.
Specifically - when a user presses a button in one view controller, a string is loaded into NSUserDefaults, which is then loaded into an array, which finally populates a table view.
I am wondering how I can load an image in each tableview cell, dependent on what string is loaded from NSUserDefaults?
I don't want to save images IN NSUserDefaults, as I am aware this is not a good idea.
What can I do?
Thank you for your time (and helping a novice out)!
Update 19FEB13
The Strings I am loading into NSUserDefaults are the names of objects, for example "ARCX".
At the moment I have tried a variety of pieces of code, but I am at the point where I seem to have a misunderstanding/lack of knowledge (or both).
UITableViewCell *XCell = [tableView cellForRowAtIndexPath:IndexPath];
NSString *content = Xcell.textLabel.text;
if ([content isEqualToString:#"ARCX"]) [UIImage *Image = [UIImage imageNamed #"ARCX.png"]];
Obviously I'm getting errors from this code.
I hope you can help!
Update 20FEB13
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *string = [myOBJArray objectAtIndex:indexPath.row];
static NSString *CellIdentifier = #"XCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
UIView *cellbackground = [[UIView alloc] initWithFrame:CGRectZero];
cellbackground.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"MSP cell bg MK2.png"]];
cell. backgroundView = cellbackground;
}
cell.textLabel.textColor = [UIColor yellowColor ];
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:24.0];
cell.textLabel.text = string;
UITableViewCell *XCell = [tableView cellForRowAtIndexPath:indexPath];
NSString *content = XCell.textLabel.text;
if ([content isEqualToString:#"ARCX"]) [UIImage *Image = [UIImage imageNamed: #"ARCX.png" ]];
cell.imageView.image = Image;
return cell;
}
I did have the code I initially posted in the CellForRowAtIndexPath, but I know I am missing something in the implementation (obviously as it doesn't work!).
Thanks for your time!
Update 19Feb13
I This is my current CellForRowAtIndexPath. No errors, but yet no images in my cells. What am I missing?
Have I got to add an image view? I am currently using a 'basic' cell, not a custom one.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *string = [myObjArray objectAtIndex:indexPath.row];
static NSString *CellIdentifier = #"MSCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
UIView *cellbackground = [[UIView alloc] initWithFrame:CGRectZero];
cellbackground.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"MSP cell bg MK2.png"]];
cell. backgroundView = cellbackground;
}
cell.textLabel.textColor = [UIColor blackColor ];
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:24.0];
cell.textLabel.text = string;
if ([string isEqualToString:#"ARCX"])
cell.imageView.image = [UIImage imageNamed: #"ARCX.png"];
else if ([string isEqualToString:#"WPX"])
cell.imageView.image = [UIImage imageNamed:#"WPX.png"];
return cell;
}
Thanks for your time!
UITableViewCell *XCell = [tableView cellForRowAtIndexPath:indexPath];
NSString *content = XCell.textLabel.text;
Please remove this piece of code, as it will call cellForRowAtIndexPath again and again.
You already have the image name as string
NSString *string = [myOBJArray objectAtIndex:indexPath.row];
So change the code like below.
if ([string isEqualToString:#"ARCX"])
UIImage *Image = [UIImage imageNamed: #"ARCX.png"];
cell.imageView.image = Image;

How to push new view from TableViewCell?

In my app I am trying to navigate to a new View from a TableViewCell, But i dont know how. Could you help guys? I am using Xcode 4.6. and .xib, no storyboard. I am very new to coding so please explain it as simple as possible! Here is what i have tried, please correct me:
- (void)viewDidLoad
{
tableData = [[NSArray alloc] initWithObjects:#"aaoversikt1", #"Paul", #"George", #"Ringo", nil];
[super viewDidLoad];
UILabel *nav_title1 = [[UILabel alloc] initWithFrame:CGRectMake(60, 10, 220, 25)];
nav_title1.font = [UIFont fontWithName:#"Arial-BoldMT" size:18];
nav_title1.textColor = [UIColor whiteColor];
nav_title1.adjustsFontSizeToFitWidth = NO;
nav_title1.textAlignment = NSTextAlignmentCenter;
nav_title1.text = #"Ă…lesund";
nav_title1.backgroundColor = [UIColor clearColor];
self.navigationItem.titleView = nav_title1;
}
#pragma mark - TableView Data Source methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection: (NSInteger)section;
{
return [tableData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
UITableViewCell *cell = nil;
static NSString *CellIdentifier = #"Cell";
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = [tableData objectAtIndex:indexPath.row];
return cell;
}
#pragma mark - TableView Delegate methods
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
AAOversiktViewController *aaoversikt1 = [[AAOversiktViewController alloc] initWithNibName:#"AAOversiktViewController" bundle:nil];
[self.navigationController pushViewController:aaoversikt1 animated:YES];
}
Thank You!
From first glance I would say that the problem lies within your [self.navigationController pushViewController] method. Have you initiated a navigation controller in your app either in the app delegate or root view controller?
If not i would recommend:
[self presentViewController:aaoversik1 animated:YES completion:NULL];
If you are wanting to push through the navigation stack so that you have a back button then I would look at implementing a UINaviationController.
Otherwise you can create a custom back button and use the same method in this post to present the root view controller (not totally recomended as using UINavigationController is much cleaner).
Let me know if this has been of any help, T

Xcode didSelectRowAtIndexPath on tableview not called

I have been looking until 6 o'clock this morning, but I can't figure out why the didSelectRowAtIndexPath method is not being called. I am getting quite desparate on this one.
The tableview is shown properly, but I cannot succeed to enable the selection of a cell.
In the header file , I added:
#interface AlertsTable : UIViewController<UITableViewDelegate, UITableViewDataSource, CMPopTipViewDelegate>{
UITableView *TableView;
}
#property (nonatomic, retain) UITableView *TableView;
In the implementation file:
#synthesize TableView;
- (void)viewDidLoad
{
[super viewDidLoad];
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
//Set the title
//Format Alerts table
//self.view.backgroundColor = [UIColor redColor];
CGFloat sideMargin = 10;
CGFloat topBottomMargin = 44;
CGFloat originX = sideMargin;
// compute width based on view size
CGFloat sizeWidth = (self.view.bounds.size.width - (sideMargin * 2));
CGFloat originY = topBottomMargin;
// compute height based on view size
CGFloat sizeHeight = (self.view.bounds.size.height - (topBottomMargin * 2));
//self.view.frame = CGRectMake(originX, originY, sizeWidth, sizeHeight);
self.TableView = [[UITableView alloc] initWithFrame:CGRectMake(originX, originY, sizeWidth, sizeHeight) style:UITableViewStylePlain];
//Initialize the array.
AlertsItems = [[NSMutableArray alloc] initWithObjects: #"Alert 1", #"Alert 2", #"Alert 3" , #"Alert 4", #"Alert 5", #"Alert 6", nil];
[self.TableView setDelegate:self];
[self.TableView setDataSource:self];
[self.view addSubview:TableView];
TableView.userInteractionEnabled = YES;
TableView.allowsSelection = YES;
TableView.allowsSelectionDuringEditing = YES;
NSLog(#"delegate:%# dataSource:%#", self.TableView.delegate, self.TableView.dataSource);
}
The delegate and datasource are both not nil on the check.
Note that the "Alertstable" inherits from a UIViewController, not a UITableViewController.
This is necessary due to the implementation I chose: the tableview is shown on a popupwindow shown on the screen (using another class that I took from the internet).
This is the didSelectRowAtIndexPath method:
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *alertString = [NSString stringWithFormat:#"Clicked on row #%d", [indexPath row]];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:alertString message:#"" delegate:self cancelButtonTitle:#"Done" otherButtonTitles:nil];
[alert show];
}
The methods:
[super touchesBegan:...];
[super touchesEnded:...];
[super touchesMoved:...];
are not implemented.
I added the AlertTable from another ViewController
AlertsTable *AlertTable = [[AlertsTable alloc] WithButton:sender withArray:self.PopTipViews];
[self.view addSubview:AlertTable.view];
I also implemented:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Set up the cell...
[[cell textLabel] setText:[AlertsItems objectAtIndex:indexPath.row]];
NSLog (#"%#",[AlertsItems objectAtIndex:indexPath.row]);
return cell;
}
Do you have any idea what the problem could be?
I'm not very experienced in Xcode and I'm really stuck.
Edit:
I know that it is not custom, but the link to the project can be found here (perhaps I'm overlooking something:
https://www.bilbu.be/BarConnect_v2.zip
The LoginViewController.xib is not properly linked (it is available in the en.lproj subfolder) so you may need to link first (I noticed too late and I had the file uploaded by a friend before - I cannot re-upload it myself unfortunately).
ViewController VC class calls the AlertsTable VC class. There is more in the project that I suppose you can ignore...
Note that the purpose of this project is only to serve as visual interface prototype. It is not meant to be the best optimized application (this is what other developers will do). If this doesn't work, I will use Photoshop to create the interfaces, but I guess that's not gonna be as convincing...
I successfully compiled your project. The problem is that you're going against the MVC pattern. The controller (AlertsTable) is inside of a view (CMPopTipView). I'd suggest you to rethink the hierarchy of the controllers and views. Hope this will help you.
Try changing
TableView.userInteractionEnabled = YES;
TableView.allowsSelection = YES;
TableView.allowsSelectionDuringEditing = YES;
to
self.TableView.userInteractionEnabled = YES;
self.TableView.allowsSelection = YES;
self.TableView.allowsSelectionDuringEditing = YES;
and are you allocating self.TableView? Something like...
self.TableView = [[UITableView alloc] init];//[[UITableView alloc] initWithStyle:UITableViewStylePlain];

iPhone UITableViewCell slow performance

I just wrote a small application that read from a site feed and display in UITableViewCell. I am using custom view cell and my UITableView is screwed in scrolling like it is not very smooth in scrolling upside down. Any idea? Here's the code for my UITableViewCell,
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"CustomCell";
CustomCell *cell = (CustomCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
// cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"CustomCell" owner:nil options:nil];
for(id currentObject in topLevelObjects) {
if([currentObject isKindOfClass:[UITableViewCell class]]) {
cell = (CustomCell *) currentObject;
break;
}
}
}
//MiceAppDelegate *AppDelegate = (MiceAppDelegate *)[[UIApplication sharedApplication] delegate];
if(dataArray != nil) {
//
//NSArray *promoArray = (NSArray *) promotions;
NSDictionary *datadict = [self.dataArray objectAtIndex:indexPath.row];
NSString *url = [datadict objectForKey:#"imageUrl"];
NSString *title = [datadict objectForKey:#"title"];
NSString *description = [datadict objectForKey:#"description"];
NSString *newAddressPartOfURL = [url stringByReplacingOccurrencesOfString:#" " withString:#"+"];
//NSLog([url stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]);
NSURLResponse *urlResponse;
NSData *data = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:newAddressPartOfURL]] returningResponse:&urlResponse error:nil];
// Configure the cell.
UIImage *urlImage = [[UIImage alloc] initWithData:data];
// NSLog(#"%i",[imageView.image topCapHeight]);
cell.title.text = title;
cell.description.text = description;
cell.image.image = urlImage;
[urlImage release];
}
return cell;
}
Doing synchronous downloads as your cells are being drawn is definitely going to cause some unsmooth scrolling. You could try to replace those with asynchronous calls, and filling in the data with a generic object while the download is happening. When the download completes, then call reloadData on your tableview.
afaik the dequeueReusableCellWithIdentifier method is called as cells get flush etc. Build your data / do the requests on init, not in the cell creation!

Resources