Dynamic collection view cell size-objective c? - objective-c

I am working on collection view in objective c,
My problem was
1.I want to change the cell size according to it's content size
2.If there are no image in cell then like and comment view should go above(refer image).
I have changed the constraint like
NSLayoutConstraint *newConstraint;
if([image isEqualToString:#"no_image.jpg"] || [image isEqualToString:#"no_image.jpg"]){
cell.desc_ImgViewWidth.constant = 0;
[cell.Descimgview setHidden:YES];
newConstraint = [NSLayoutConstraint constraintWithItem:(cell.bottomConstraint).firstItem attribute:(cell.bottomConstraint).firstAttribute relatedBy:NSLayoutRelationGreaterThanOrEqual toItem:(cell.bottomConstraint).secondItem attribute:(cell.bottomConstraint).secondAttribute multiplier:(cell.bottomConstraint).multiplier constant:(cell.bottomConstraint).constant];
}
else{
cell.desc_ImgViewWidth.constant = 120;
[cell.Descimgview setHidden:NO];
newConstraint = [NSLayoutConstraint constraintWithItem:(cell.bottomConstraint).firstItem attribute:(cell.bottomConstraint).firstAttribute relatedBy:NSLayoutRelationEqual toItem:(cell.bottomConstraint).secondItem attribute:(cell.bottomConstraint).secondAttribute multiplier:(cell.bottomConstraint).multiplier constant:(cell.bottomConstraint).constant];
}
[cell.contentView removeConstraint:(cell.bottomConstraint)];
[cell.contentView addConstraint:newConstraint];
[cell layoutIfNeeded];
[[cell contentView] setFrame:[cell bounds]];
[[cell contentView] setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
in cellForItemAtIndexPath delegate method.(like and comment view moving above at first, but after reloading the cell again i.e, like scrolling etc the constraint is not working perfectly)
I want to move like and comment view like this and to reduce the cell height for that particular cell(refer below image)
How to properly do this?

You can use UICollectionViewLayout
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
if imageView != nil
{
return CGSizeMake(width, height)
}
else
{
return CGSizeMake(width, height)
}
}

Finally achieved like this,
- (CGSize)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout *)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary* object = [_Data objectAtIndex:indexPath.item];
NSString *image = [object valueForKey:#"image"];
if([image isEqualToString:#"no_image.jpg"] || [image isEqualToString:#"no_image.jpg"]){
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
float cellWidth = screenWidth;
NSDictionary* object = [_Data objectAtIndex:indexPath.item];
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[SwiftHelper getEmojiText:[object valueForKey:#"description"]]];
[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:#"Georgia" size:15.0] range:NSMakeRange(0, str.length)];
CGSize sizeName = CGRectIntegral([str boundingRectWithSize:CGSizeMake(cellWidth-8, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin context:nil]).size;
NSMutableAttributedString *str1 = [[NSMutableAttributedString alloc] initWithString:[SwiftHelper getEmojiText:[object valueForKey:#"name"]]];
[str1 addAttribute:NSFontAttributeName value:[UIFont fontWithName:#"Georgia" size:15.0] range:NSMakeRange(0, str1.length)];
CGSize sizeName1 = CGRectIntegral([str1 boundingRectWithSize:CGSizeMake(cellWidth-8, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin context:nil]).size;
NSLog(#"%f,%f",sizeName.height,sizeName1.height);
if(sizeName.height > 100){
sizeName.height = 70;
}
return CGSizeMake(cellWidth, sizeName.height + sizeName1.height + 110);
}
else{
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
float cellWidth = screenWidth;
CGSize size = CGSizeMake(cellWidth, 182);
return size;
}
Thank you for your suggestions friends.
Really it's better to use tableview for this but unfortunately after using collection view for a previous design the requirement changed like this. So, I struggled.

Related

UIlabel height issue in Custom UItableViewCell in iOS 6 and iOS 7

i am displaying different items in custom table cell. when i try to display multiline uilabel text. it si only showing single line. even though i calculate the label height
also i try to set new frame with new height after calculation.
my code is as follows:
+(CGRect )getlabelHeight:(CGRect)frame withFontName:(NSString *)font andFontSize:(float)fontSize andText:(NSString *)text
{
CGSize constrainedSize = CGSizeMake(frame.size.width, 9999);
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont fontWithName:font size:fontSize], NSFontAttributeName,
nil];
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:text attributes:attributesDictionary];
CGRect requiredHeight = [string boundingRectWithSize:constrainedSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];
if (requiredHeight.size.width > constrainedSize.width) {
requiredHeight = CGRectMake(0,0, constrainedSize.width, requiredHeight.size.height);
}
CGRect newFrame = frame;
newFrame.size.height = requiredHeight.size.height;
frame = newFrame;
return frame;
}
my tabelview method is as follows:
CGRect descFrame=[Utility getlabelHeight:CGRectMake(65,35+titleFrame.size.height, 250, 20) withFontName:appFont andFontSize:15 andText:[[allComments objectAtIndex:indexPath.row]valueForKey:#"comment"]];
NSLog(#"%# \n %f",[[allComments objectAtIndex:indexPath.row]valueForKey:#"comment"],descFrame.size.height);
[cell.title setFont:[UIFont fontWithName:appFont size:15]];
[cell.title setText:[[allComments objectAtIndex:indexPath.row]valueForKey:#"comment"]];
[cell.title setLineBreakMode:NSLineBreakByWordWrapping];
[cell.title setNumberOfLines:0];
[cell.title setFrame:descFrame];
[cell.title setTextColor:[UIColor blackColor]];
Please help me!!1 i am screwed...
thanks you!!!

NSMutableArray not holding UIImages properly?

I have enabled my Cocoa Touch app to be navigable by swiping left or right to alter positions in history. The animation is kind of done like Android's "card" style. Where swiping to the left (<--) just moves the current screen image out of the way, while showing the previous view beneath it.
This works fine, but when I want to swipe the other way (-->), to go back, I need to get the previous image, and move that over the current view. Now, I had this working if I only store the previous image, but what if I go <-- a few times, then I will not have enough images.
So, the solution is obvious, use an NSMutableArray and just throw the latest image at the front of the array, and when you swipe the other way, just use the first image in the array. However, the image never shows when I start the animation. It just shows nothing. Here's the required methods you should see:
-(void)animateBack {
CGRect screenRect = [self.view bounds];
UIImage *screen = [self captureScreen];
[imageArray insertObject:screen atIndex:0]; //Insert the screenshot at the first index
imgView = [[UIImageView alloc] initWithFrame:screenRect];
imgView.image = screen;
[imgView setHidden:NO];
NSLog(#"Center of imgView is x = %f, y = %f", imgView.center.x, imgView.center.y);
CGFloat startPointX = imgView.center.x;
CGFloat width = screenRect.size.width;
NSLog(#"Width = %f", width);
imgView.center = CGPointMake(imgView.center.x, imgView.center.y);
[self.view addSubview: imgView];
[self navigateBackInHistory];
[UIView animateWithDuration:.3 animations:^{
isSwiping = 1;
imgView.center = CGPointMake(startPointX - width, imgView.center.y);
} completion:^(BOOL finished){
// Your animation is finished
[self clearImage];
isSwiping = 0;
}];
}
-(void)animateForward {
CGRect screenRect = [self.view bounds];
//UIImage *screen = [self captureScreen];
UIImage *screen = [imageArray objectAtIndex:0]; //Get the latest image
imgView = [[UIImageView alloc] initWithFrame:screenRect];
imgView.image = screen;
[imgView setHidden:NO];
NSLog(#"Center of imgView is x = %f, y = %f", imgView.center.x, imgView.center.y);
CGFloat startPointX = imgView.center.x;
CGFloat width = screenRect.size.width;
NSLog(#"Width = %f", width);
imgView.center = CGPointMake(imgView.center.x - width, imgView.center.y);
[self.view addSubview: imgView];
[UIView animateWithDuration:.3 animations:^{
isSwiping = 1;
imgView.center = CGPointMake(startPointX, imgView.center.y);
} completion:^(BOOL finished){
// Your animation is finished
[self navigateForwardInHistory];
[self clearImage];
isSwiping = 0;
}];
}
-(void)clearImage {
[imgView setHidden:YES];
imgView.image = nil;
}
-(void)navigateBackInHistory {
[self saveItems:self];
[self alterIndexBack];
item = [[[LEItemStore sharedStore] allItems] objectAtIndex:currentHistoryIndex];
[self loadItems:self];
}
-(void)navigateForwardInHistory {
[imageArray removeObjectAtIndex:0]; //Remove the latest image, since we just finished swiping this way.
[self saveItems:self];
[self alterIndexForward];
item = [[[LEItemStore sharedStore] allItems] objectAtIndex:currentHistoryIndex];
[self loadItems:self];
}
Note that imgView is a class-level UIImageView and imageArray is a class level array.
Any ideas? Thanks.
Edit
Here's the code at the top of my .m to initalize it. Still does not work.
.....
NSMutableArray *imageArray;
- (void)viewDidLoad
{
[super viewDidLoad];
imageArray = [imageArray initWithObjects:nil];
It looks like you forgot to create the array. Something like this at the appropriate time would do (assuming ARC):
imageArray = [NSMutableArray array];
Glad that worked out.

How to calculate the Width and Height of NSString on UILabel

I am working on a project to make the NSString on UILabel Width and Height dynamically.
I tried with:
NSString *text = [messageInfo objectForKey:#"compiled"];
writerNameLabel.numberOfLines = 0;
writerNameLabel.textAlignment = UITextAlignmentRight;
writerNameLabel.backgroundColor = [UIColor clearColor];
CGSize constraint = CGSizeMake(296,9999);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE]
constrainedToSize:constraint
lineBreakMode:UILineBreakModeWordWrap];
NSLog(#"sizewidth = %f, sizeheight = %f", size.width, size.height);
NSLog(#"writerNameLabel.frame.size.width 1 -> %f",writerNameLabel.frame.size.width);
[writerNameLabel setFrame:CGRectMake(writerNameLabel.frame.origin.x, writerNameLabel.frame.origin.y, size.width, size.height)];
CGRect labelFram = writerNameLabel.frame;
labelFram.origin.x = cell.frame.size.width - writerNameLabel.frame.size.width - 80;
writerNameLabel.frame = labelFram;
NSLog(#"writerNameLabel.frame.size.width 2-> %f",writerNameLabel.frame.size.width);
Please see the green bubble not the grey one.
Still not right.
The code for bubble
bubbleImageView.frame = CGRectMake(writerNameLabel.frame.origin.x, writerNameLabel.frame.origin.y, writerNameLabel.frame.size.width+15, writerNameLabel.frame.size.height+5);
Please Advise! Thanks!
That's because you did not reuse the table cell, the structure should be like:
NSString *text = [messageInfo objectForKey:#"compiled"];
if(cell == nil)
{
writerNameLabel.numberOfLines = 0;
writerNameLabel.textAlignment = UITextAlignmentRight;
writerNameLabel.backgroundColor = [UIColor clearColor];
[cell addSubview:writerNameLabel];
}
else {
writerNameLabel = (UILabel *)[cell viewWithTag:WRITER_NAME_LABEL_TAG];
}
CGSize constraint = CGSizeMake(296,9999);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE]
constrainedToSize:constraint
lineBreakMode:UILineBreakModeWordWrap];
[writerNameLabel setFrame:CGRectMake(writerNameLabel.frame.origin.x, writerNameLabel.frame.origin.y, size.width, size.height)];
I've been gone through and answered some of your question, that's correct way to write your tableview controller. And your problem will be solved.

Why images are not showing in UIScrollView?

I am using this code to show scrolling images but I am only getting a white screen. I drag drop uiscrollview, created the iboutlet, synthesized it and rest of the code is here
#synthesize scrollView1;
const CGFloat kScrollObjHeight = 199.0;
const CGFloat kScrollObjWidth = 280.0;
const NSUInteger kNumImages = 5;
- (void)layoutScrollImages
{
UIImageView *view = nil;
NSArray *subviews = [scrollView1 subviews];
// reposition all image subviews in a horizontal serial fashion
CGFloat curXLoc = 0;
for (view in subviews)
{
if ([view isKindOfClass:[UIImageView class]] && view.tag > 0)
{
CGRect frame = view.frame;
frame.origin = CGPointMake(curXLoc, 0);
view.frame = frame;
curXLoc += (kScrollObjWidth);
}
}
// set the content size so it can be scrollable
[scrollView1 setContentSize:CGSizeMake((kNumImages * kScrollObjWidth), [scrollView1 bounds].size.height)];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
scrollView1 = [[UIScrollView alloc]init];
bgArray = [NSArray arrayWithObjects:#"Bg", #"Bg1.png", #"Bg2.png", #"Bg3.png", #"Bg4.png", #"Bg5.png", #"Bg6.png", #"Bg7.png", #"Bg8.png", nil];
[scrollView1 setBackgroundColor:[UIColor blackColor]];
[scrollView1 setCanCancelContentTouches:NO];
scrollView1.indicatorStyle = UIScrollViewIndicatorStyleWhite;
scrollView1.clipsToBounds = YES; // default is NO, we want to restrict drawing within our scrollview
scrollView1.scrollEnabled = YES;
// pagingEnabled property default is NO, if set the scroller will stop or snap at each photo
// if you want free-flowing scroll, don't set this property.
scrollView1.pagingEnabled = YES;
// load all the images from our bundle and add them to the scroll view
NSUInteger i;
for (i = 0; i < [bgArray count]; i++)
{
NSString *imageName = [NSString stringWithFormat:#"%#", [bgArray objectAtIndex:i]];
UIImage *image = [UIImage imageNamed:imageName];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
// setup each frame to a default height and width, it will be properly placed when we call "updateScrollList"
CGRect rect = imageView.frame;
rect.size.height = 199.0;
rect.size.width = 280.0;
imageView.frame = rect;
imageView.tag = i; // tag our images for later use when we place them in serial fashion
[scrollView1 addSubview:imageView];
[scrollView1 setShowsHorizontalScrollIndicator:NO];
[scrollView1 setShowsVerticalScrollIndicator:NO];
}
[self layoutScrollImages];
}
I think if you are create UIScrollView from code
scrollView1 = [[UIScrollView alloc]init];
then please add the scrollView1 in view
Example:-[self.view addSubview:scrollView1];
if you are create UIScrollView from nib then
not use this code
scrollView1 = [[UIScrollView alloc]init];
solve your probem

How to add sound while UIScrollview is scrolling in iphone sdk?

This is my code for adding sound while UIScrollview is scrolling in iPhone SDK. In this code, how to add the sound while using touch-events in scrolling?
Please give me your idea and suggestion or sample.
const CGFloat kScrollObjHeight = 151.0;
const CGFloat kScrollObjWidth =320.0;
const NSUInteger kNumImages = 5;
- (void)layoutScrollImages
{
UIImageView *view = nil;
NSArray *subviews = [scrollView1 subviews];
CGFloat curXLoc = 0;
for (view in subviews)
{
if ([view isKindOfClass:[UIImageView class]] && view.tag > 0)
{
CGRect frame = view.frame;
frame.origin = CGPointMake(curXLoc, 0);
view.frame = frame;
curXLoc += (kScrollObjWidth);
}
}
[scrollView1 setContentSize:CGSizeMake((kNumImages * kScrollObjWidth), [scrollView1 bounds].size.height)];
}
- (void)viewDidLoad
{
self.view.backgroundColor = [UIColor clearColor];
[scrollView1 setBackgroundColor:[UIColor whiteColor]];
[scrollView1 setCanCancelContentTouches:NO];
scrollView1.indicatorStyle = UIScrollViewIndicatorStyleWhite;
scrollView1.clipsToBounds = YES;
scrollView1.scrollEnabled = YES;
scrollView1.pagingEnabled = YES;
NSUInteger i;
for (i = 1; i <= kNumImages; i++)
{
NSString *imageName = [NSString stringWithFormat:#"snap%d.jpg", i];
UIImage *image = [UIImage imageNamed:imageName];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
CGRect rect = imageView.frame;
rect.size.height = kScrollObjHeight;
rect.size.width = kScrollObjWidth;
imageView.frame = rect;
imageView.tag = i;
[scrollView1 addSubview:imageView];
[imageView release];
[self layoutScrollImages];
}
[super viewDidLoad];
}
add UIScrollViewDelegate to your interface and then play sound while the scrolling is in task in scrollViewWillBeginDragging state and stop scrolling while in scrollViewDidEndDragging state.
You can use AVAudioPlayer to play sound on iOS devices
UPDATE:
Tells the delegate when the scroll view is about to start scrolling the content.
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
Also, Tells the delegate when dragging ended in the scroll view.
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
Implement these in your code & put in your custom behavior
you mast use UIScrollViewDelegate method
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
//play sound here
}