iOS:Dispaly label with text on collectionView cell on long press - ios7

I want to display label with text on collectionViewCell on long press.
Text which i want to display is coming from array.
Following is my code:
// This code is in cellForItemAtIndexPath method
// attach long press gesture to collectionView
UILongPressGestureRecognizer *lpgr= [[UILongPressGestureRecognizer alloc]
initWithTarget:self action:#selector(handleLongPress:)];
lpgr.minimumPressDuration = .5; //seconds
lpgr.delegate = self;
[collectionViewAlbumImages addGestureRecognizer:lpgr];
lpgr.delaysTouchesBegan = YES;
-(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer
{
if (gestureRecognizer.state != UIGestureRecognizerStateEnded) {
return;
}
CGPoint p = [gestureRecognizer locationInView:collectionViewAlbumImages];
NSIndexPath *indexPath = [collectionViewAlbumImages indexPathForItemAtPoint:p];
if (indexPath == nil){
NSLog(#"couldn't find index path");
} else {
// get the cell at indexPath (the one you long pressed)
UICollectionViewCell* cell =[collectionViewAlbumImages cellForItemAtIndexPath:indexPath];
globalVariable = [GlobalBrogaard sharedInstanceMethod];
strCellImageName = [NSString stringWithFormat: #"%#",[globalVariable.arrImageName objectAtIndex:indexPath.row]];
NSLog(#"cell %f , %f",cell.frame.origin.x, cell.frame.origin.y);
// Init and add label
lblImageName = [[UILabel alloc] initWithFrame:CGRectMake(cell.frame.origin.x, cell.frame.origin.y, 200, 200)];
lblImageName.layer.cornerRadius=6;
lblImageName.clipsToBounds=NO;
lblImageName.text = strCellImageName;
[lblImageName setTextAlignment:NSTextAlignmentLeft];
lblImageName.lineBreakMode = NSLineBreakByCharWrapping;
lblImageName.numberOfLines = 0;
lblImageName.font = [UIFont systemFontOfSize:14];
lblImageName.textColor = [UIColor whiteColor];
lblImageName.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.6];
[lblImageName sizeToFit];
[cell addSubview:lblImageName];
[lblImageName setAlpha:0.0f];
//fade in
[UIView animateWithDuration:2.0f animations:^{
[lblImageName setAlpha:1.0f];
} completion:^(BOOL finished) {
//fade out
[UIView animateWithDuration:2.0f animations:^{
[lblImageName setAlpha:0.0f];
[lblImageName removeFromSuperview];
} completion:nil];
}];
}}
but issue is it works only for first collection view cell long press and on remaining cells it will not display any label.
Please tell me what is wrong in my code??

I have solved the issue by changing this line:
lblImageName = [[UILabel alloc] initWithFrame:CGRectMake(cell.frame.origin.x, cell.frame.origin.y, 200, 200)];
to:
lblImageName = [[UILabel alloc] initWithFrame:CGRectMake(0,0, 200, 200)];

Related

remove objects from array based on the index

I have array of images here i am doing check and uncheck the images finally i have delete button which are the images i check i need to remove the images from array based on the button selection
here is my code
- (IBAction)delete_btn_touch:(id)sender {
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
for(int i=0; i<_GalleryimageArry.count;i++){
_imageV = [[UIImageView alloc]initWithFrame:CGRectMake(CGRectGetWidth(self.view.frame) * i/2*0.6, 0, 100, 100)];
self.Crossbtn =[[UIButton alloc]initWithFrame:CGRectMake(_imageV.image.size.width/2+80,0,20,20)];
UIImage *btnImage = [UIImage imageNamed:#"unselectimag"];
[self.Crossbtn setImage:btnImage forState:UIControlStateNormal];
_imageV.contentMode = UIViewContentModeScaleAspectFill;
_imageV.image = [_GalleryimageArry objectAtIndex:i];
[_imageV setUserInteractionEnabled:YES];
_imageV.tag = i;
self.Crossbtn.tag =i;
[self.Crossbtn addTarget:self action:#selector(deleteImage:) forControlEvents:UIControlEventTouchUpInside];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(imageTapMethod:)];
[_imageV addGestureRecognizer:tap];
[self.imageV addSubview:self.Crossbtn];
[self.imageGalleryscroll addSubview:_imageV];
[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}
self.imageGalleryscroll.delegate = self;
index=0;
self.imageGalleryscroll.contentSize = CGSizeMake(CGRectGetWidth(self.view.frame) * _GalleryimageArry.count/2*0.7, CGRectGetHeight(self.imageGalleryscroll.frame));
[self.imageGalleryscroll setPagingEnabled:YES];
[self.imageGalleryscroll setShowsHorizontalScrollIndicator:NO];
self.imageGalleryscroll.alwaysBounceVertical = NO;
[MBProgressHUD hideHUDForView:self.view animated:YES];
}
-(void)deleteImage:(UIButton *)sender{
btn = (UIButton *)sender;
self.add_delete_view.hidden =YES;
self.deleteview.hidden=NO;
if( [[btn imageForState:UIControlStateNormal] isEqual:[UIImage imageNamed:#"unselectimag"]])
{
[btn setImage:[UIImage imageNamed:#"Crossimg"] forState:UIControlStateNormal];
[btn setSelected:YES];
[btn setTag:index];
}
else
{
[btn setImage:[UIImage imageNamed:#"unselectimag"] forState:UIControlStateNormal];
// other statements
self.selectedimages =#"No";
image = [self.GalleryimageArry objectAtIndex:index];
[self.GalleryimageArry addObject:image];
}
NSLog(#"%#", self.GalleryimageArry);
}
- (IBAction)delete_all_img_btn_touch:(id)sender {
// self.view (change it with your button superview)
if (btn.selected) {
[self.GalleryimageArry removeObjectAtIndex:index];
}
//here i need to removeObjectAtIndex:index based on the how many button are selected
}
any one help me to solve this issues
thanks in advance
Use the following code, where you want to clear the back stack of controllers.
-(void)clearStack
{
NSMutableArray *navigationArray = [[NSMutableArray alloc] initWithArray: self.navigationController.viewControllers];
[navigationArray removeAllObjects];
//[navigationArray removeObjectAtIndex: 2];
self.navigationController.viewControllers = navigationArray;
}

how to change UISearchBar textfield background color and text color in ios8

I used below code for changing UISearchBar textfield background color.
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setDefaultTextAttributes:#{
NSForegroundColorAttributeName : [UIColor redColor],
NSFontAttributeName : [UIFont systemFontOfSize:15]
}];
but it does not work for me, can any one give solution.
thanks in advance
Try this:
UITextField *searchField = [self.searchBar valueForKey:#"searchField"];
// To change background color
searchField.backgroundColor = [UIColor blueColor];
// To change text color
searchField.textColor = [UIColor redColor];
// To change placeholder text color
searchField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:#"Some Text"];
UILabel *placeholderLabel = [searchField valueForKey:#"placeholderLabel"];
placeholderLabel.textColor = [UIColor grayColor];
Just try this code
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setBackgroundColor:[UIColor grayColor]];
OR
Try this
- (void)viewDidLoad
{
[super viewDidLoad];
//change the background color
[[self searchViewForTextFieldBg:self.searchTextfield] setBackgroundColor:[UIColor grayColor]];
//change the textcolor
self.searchTextfield.textColor =[UIColor greenColor];
}
- (UITextField*)searchViewForTextFieldBg:(UIView*)view
{
if ([view isKindOfClass:[UITextField class]]) {
return (UITextField*)view;
}
UITextField *searchTextField;
for (UIView *subview in view.subviews) {
searchTextField = [self searchViewForTextFieldBg:subview];
if (searchTextField) {
break;
}
}
return searchTextField;
}

Expand UITableViewCell with animation

I'm trying to implement functionality in my UITableView where a UITableViewCell's UIImageView expands to fill up the complete view after a user touches the cell.
This is the animation I'm using:
UITableViewCell *cell = [_tableView cellForRowAtIndexPath:indexPath];
UIImageView *imageView = [cell viewWithTag:1];
UIView *cellView = [cell viewWithTag:2];
CGRect rectInTableView = [_tableView rectForRowAtIndexPath:indexPath];
[UIView animateWithDuration:0.5
delay:0
options:UIViewAnimationOptionCurveEaseIn
animations:^(void)
{
imageView.frame = rectInTableView;
imageView.tag = 123;
[self.navigationController.view addSubview:imageView];
[imageView setFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height+64)];
imageView.contentMode = UIViewContentModeScaleAspectFill;
}
completion:^(BOOL finished)
{}];
What happens now, though, is that a UIImageView jumps to the top and then expands. I want it to expand from the cell though. How can I do this?
This might accomplish what you're trying to do:
UITableViewCell *cell = [_tableView cellForRowAtIndexPath:indexPath];
UIImageView *imageView = [cell viewWithTag:1];
UIView *cellView = [cell viewWithTag:2];
CGRect rectInTableView = [_tableView rectForRowAtIndexPath:indexPath];
imageView.frame = rectInTableView;
imageView.tag = 123;
[self.navigationController.view addSubview:imageView];
[UIView animateWithDuration:0.5
delay:0
options:UIViewAnimationOptionCurveEaseIn
animations:^(void)
{
[imageView setFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height+64)];
imageView.contentMode = UIViewContentModeScaleAspectFill;
}
completion:^(BOOL finished)
{}];

Two lines of text on UIButton with different fonts each

I found a way to add two lines of text on a UIButton,
but what I want is that each of these lines of texts
have different font (for instance one is bold, other not).
How is it possible to do this?
Thanks.
You should add 2 UILabel to the UIButton as subviews.
You can do it like:
UIButton *testButton = [UIButton buttonWithType:UIButtonTypeCustom];
testButton.frame = CGRectMake(0, 0, 200, 40);
[self.view addSubview:testButton];
UILabel *firstLineTestButton = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 20)];
firstLineTestButton.text = #"First line";
firstLineTestButton.font = [UIFont systemFontOfSize:12];
[testButton addSubview:firstLineTestButton];
UILabel *secondLineTestButton = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, 200, 20)];
secondLineTestButton.text = #"Second line";
secondLineTestButton.font = [UIFont boldSystemFontOfSize:12];
[testButton addSubview:secondLineTestButton];
To also make highlighting possible for the UILabels, you need to make the highlighting of the button custom.
So add the actions to the button and then check the button subviews for the labels and change their colors.
[testButton addTarget:self action:#selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
[testButton addTarget:self action:#selector(changeColor:) forControlEvents:UIControlEventTouchDown];
[testButton addTarget:self action:#selector(touchCancel:) forControlEvents:UIControlEventTouchDragExit];
-(void)buttonAction:(UIButton*)sender
{
[self touchCancel:sender];
/* DO SOME MORE ACTIONS */
}
-(void)changeColor:(UIButton*)sender
{
sender.backgroundColor = [UIColor grayColor];
for( UIView *subview in sender.subviews ){
if( [subview isKindOfClass:[UILabel class]] ){
UILabel *subViewLabel = (UILabel*)subview;
subViewLabel.textColor = [UIColor blueColor];
}
}
}
-(void)touchCancel:(UIButton*)sender
{
sender.backgroundColor = [UIColor clearColor];
for( UIView *subview in sender.subviews ){
if( [subview isKindOfClass:[UILabel class]] ){
UILabel *subViewLabel = (UILabel*)subview;
subViewLabel.textColor = [UIColor blackColor];
}
}
}
The solution of Roland is good, another way to do this would be to use a NSAttributedString. The downside is, that it only works in iOS 6 and above.
If this is not a problem, here is the code
- (void)viewDidLoad
{
[super viewDidLoad];
// We want 2 lines for our buttons' title label
[[self.button titleLabel] setNumberOfLines:2];
// Setup the string
NSMutableAttributedString *titleText = [[NSMutableAttributedString alloc] initWithString:#"This should be bold,\n and this should not."];
// Set the font to bold from the beginning of the string to the ","
[titleText addAttributes:[NSDictionary dictionaryWithObject:[UIFont boldSystemFontOfSize:14] forKey:NSFontAttributeName] range:NSMakeRange(0, 20)];
// Normal font for the rest of the text
[titleText addAttributes:[NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:14] forKey:NSFontAttributeName] range:NSMakeRange(20, 22)];
// Set the attributed string as the buttons' title text
[self.button setAttributedTitle:titleText forState:UIControlStateNormal];
}
You can add two UILabels as subview of the button and then can set the text of the labels as
[lbl1 setFont:[UIFont fontWithName:#"Arial-Bold" size:18]];
[lbl2 setFont:[UIFont fontWithName:#"Arial" size:16]];
For proper animation, you should subclass UIButton and redraw it when its state changes.
(void)drawRect:(CGRect)rect
{
if (!self.firstLineTestButton) {
self.firstLineTestButton = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 20)];
self.firstLineTestButton.text = #"First line";
self.firstLineTestButton.font = [UIFont systemFontOfSize:12];
[self addSubview:self.firstLineTestButton];
}
if (!self.secondLineTestButton) {
self.secondLineTestButton = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, 200, 20)];
self.secondLineTestButton.text = #"Second line";
self.secondLineTestButton.font = [UIFont boldSystemFontOfSize:12];
[self addSubview:self.secondLineTestButton];
}
if (!self.highlighted) {
// Do custom drawing such as changing text color
} else {
// Do custom drawing such as changing text color
}
}
(void)setHighlighted:(BOOL)highlighted {
[super setHighlighted:highlighted];
// Force redraw of button
[self setNeedsDisplay];
}

UITableViewCell - overlapping with previous cells contents

I have this wierd problem with my table
i Have about 20 cells to display
Each cell is about 84px in height
When i click no the cell, i have set a background colour
The first 4 cells are ok, but when i scroll down and click on the 5th cell, the content of each cell starts to overlap with some other content, usually content from 1st 4 cells.
I belive its some cell reusability or drawing issue. Am not sure how to solve it, i have checked through my code, but i am not changing the cell's content on touch.
Here is my code and will add some pics too
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 104;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [stores count];
}
-(UITableViewCell *)tableView:(UITableView *) tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
CGRect Label1Frame = CGRectMake(5, 5, 250, 30);
CGRect Label2Frame = CGRectMake(6, 42, 220, 20);
CGRect Label3Frame = CGRectMake(6, 62, 220, 20);
CGRect Label4Frame = CGRectMake(240,56, 70, 12);
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
}else{
// a cell is being recycled, remove the old edit field (if it contains one of our tagged edit fields)
UIView *viewToCheck = nil;
viewToCheck = [cell.contentView viewWithTag:1];
if (!viewToCheck) {
[viewToCheck removeFromSuperview];
DebugLog(#"View removed");
}
}
//cell.selectionStyle=UITableViewCellSelectionStyleNone;
[cell setSelectedBackgroundView:bgView];
NSInteger row=indexPath.row;
UILabel *lblTemp;
[[cell contentView] clearsContextBeforeDrawing];
//Line 1
lblTemp=[[UILabel alloc] initWithFrame: Label1Frame];
lblTemp.tag=1;
lblTemp.text=[[stores objectAtIndex:row] objectAtIndex:0] ;
lblTemp.numberOfLines=2;
lblTemp.font = [UIFont boldSystemFontOfSize:13];
lblTemp.adjustsFontSizeToFitWidth=YES;
lblTemp.minimumFontSize=12;
lblTemp.textColor = [UIColor grayColor];
[cell.contentView addSubview:lblTemp];
[lblTemp release];
//Line 2
lblTemp = [[UILabel alloc] initWithFrame:Label2Frame];
lblTemp.tag = 2;
lblTemp.text=[[stores objectAtIndex:row]objectAtIndex:1];
lblTemp.font = [UIFont systemFontOfSize:12];
lblTemp.textColor = [UIColor grayColor ];
lblTemp.textAlignment=UITextAlignmentLeft;
lblTemp.adjustsFontSizeToFitWidth=YES;
lblTemp.minimumFontSize=12;
[cell.contentView addSubview:lblTemp];
[lblTemp release];
//Line 3
lblTemp = [[UILabel alloc] initWithFrame:Label3Frame];
lblTemp.tag = 3;
lblTemp.text=[[stores objectAtIndex:row]objectAtIndex:2];
lblTemp.font = [UIFont systemFontOfSize:12];
lblTemp.textColor = [UIColor grayColor ];
[cell.contentView addSubview:lblTemp];
[lblTemp release];
//Phone button
UIButton *phoneButton=[[UIButton alloc] initWithFrame:CGRectMake(240,16,30,30)];
[phoneButton setBackgroundImage:[UIImage imageNamed:#"phone.png"] forState:UIControlStateNormal];
[phoneButton setTag:row];
[phoneButton addTarget:self action:#selector(dialNumber:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:phoneButton];
//ANnotation button
UIButton *annotation=[[UIButton alloc] initWithFrame:CGRectMake(274,16,30,30)];
[annotation setTag:row];
[annotation setBackgroundImage:[UIImage imageNamed:#"tab.png"] forState:UIControlStateNormal];
[annotation addTarget:self action:#selector(openMap:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:annotation];
[annotation release];
//Distance label
//Line 3
lblTemp = [[UILabel alloc] initWithFrame:Label4Frame];
lblTemp.tag = 4;
lblTemp.text=[[stores objectAtIndex:row]objectAtIndex:5];
lblTemp.textAlignment=UITextAlignmentCenter;
lblTemp.font = [UIFont systemFontOfSize:13];
lblTemp.textColor = [UIColor grayColor ];
[lblTemp setAdjustsFontSizeToFitWidth:YES];
[cell.contentView addSubview:lblTemp];
[phoneButton release];
[lblTemp release];
[cell setNeedsLayout];
[cell setNeedsDisplay];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell=[tableView cellForRowAtIndexPath:indexPath ];
for(UILabel *lbl in cell.contentView.subviews){
if([lbl isKindOfClass:[UILabel class]]){
lbl.textColor=[UIColor whiteColor];
}
}
//UITableViewCell *cell1;
//NSString *row=[NSString stringWithFormat:#"%d",indexPath.row];
svm = [[storesMapView alloc] initWithNibName:#"storesMapView" bundle:nil];
[svm initWithXML:stores:indexPath.row];
CGRect theFrame = svm.view.frame;
theFrame.origin = CGPointMake(self.view.frame.size.width, 0);
svm.view.frame = theFrame;
theFrame.origin = CGPointMake(0,0);
theFrame.size=CGSizeMake(320,355);
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.3f];
svm.view.frame = theFrame;
[UIView commitAnimations];
[subView addSubview:svm.view];
backButton.hidden=NO;
}
I figured it out with some trial and error; if this can help some one
In cellforRowAtIndexPath i tried to clear all the cells subview before drawing the cell
//TRY TO REMOVE ALL CONTENT
for(UIView *view in cell.contentView.subviews){
if ([view isKindOfClass:[UIView class]]) {
[view removeFromSuperview];
}
}
I would be happy if someone can point me to some easier way
Thanks
You can use
[[[cell contentView] subviews] makeObjectsPerformSelector: #selector(removeFromSuperview)];
If the cell in not nil, the above code will reduce the time for using the for loop similar to this
for(UIView *eachView in [cell subviews])
[eachView removeFromSuperview];
I also had the same issue.I also had composed tableView with labels.And when I scroll it down the contents got overlapped.But it got solved simply by editing one statement in cellForRowAtIndexPath.
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:nil];
I think this will solve your problem.
I know this is a bit late, but I had a similar issue where UILabels created for a cell were still part of the cell when it was reused. So each successive update of the tableview created another UILabel on top of the existing one. I moved the creation of the Labels into the if condition as below and it resolved my issue. Hope it helps someone else. Also note no release as I am using ARC.
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cityText = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 20)];
cityText.font = [UIFont fontWithName:#"Arial" size:20];
cityText.textAlignment = UITextAlignmentLeft;
cityText.backgroundColor = [UIColor clearColor];
regionText = [[UILabel alloc] initWithFrame:CGRectMake(10, 40, 100, 20)];
regionText.font = [UIFont fontWithName:#"Arial" size:20];
regionText.textAlignment = UITextAlignmentLeft;
regionText.backgroundColor = [UIColor clearColor];
}
Setting nil to label text on UITableViewCell subclass 's method prepareForReuse() solved my problem -
override func prepareForReuse() {
super.prepareForReuse()
self.label1.text = nil
self.label2.text = nil
....
}
Shared if it helps anyone!