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

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!!!

Related

Dynamic collection view cell size-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.

UINavigationBar navigationItem title height

I am using custom font and uppercased text for navigation item title text which contain diacritics. Problem is, the diacritics is cut from top, probably because the title label has wrong height.
So question is, can I affect the title label height? Or access directly the title label and do something like sizeToFit, or change frame or something.
// custom font settings
NSDictionary *attr = #{
NSFontAttributeName: [UIFont fontWithName:#"FishmongerK-XCondLight" size:23.0],
NSForegroundColorAttributeName: [UIColor whiteColor]
};
[[UINavigationBar appearance] setTitleTextAttributes: attr];
// then setting of title
self.navigationItem.title = [NSLocalizedString(#"Oblíbené", nil) uppercaseString];
If i try smaller font size, diacritics is still cut from top.
-(void)setCustomNavTitle:(NSString*)title andDescription:(NSString*)desc {
NSString * locname = [NSString stringWithFormat:#"%#\n", title];
NSString * cityname = [NSString stringWithFormat:#"%#", desc];
NSString * text = [NSString stringWithFormat:#"%#%#", [locname capitalizedString], cityname];
NSDictionary *attribs = #{
NSForegroundColorAttributeName:[UIColor colorWithHexString:#"222222"],
NSFontAttributeName: [UIFont fontWithName:[[Variables getInstance] HelveticaNeue] size:14]
};
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:text attributes:attribs];
NSRange range = [text rangeOfString:cityname];
[attributedText setAttributes:#{NSForegroundColorAttributeName:[UIColor colorWithHexString:#"222222"],
NSFontAttributeName:[UIFont fontWithName:[[Variables getInstance] HelveticaNeueLight] size:14]} range:range];
UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 120, 44)];
titleLabel.font = [UIFont fontWithName:[[Variables getInstance] HelveticaNeueMedium] size:15];
titleLabel.attributedText = attributedText;
titleLabel.backgroundColor = [UIColor clearColor];
titleLabel.textAlignment = NSTextAlignmentCenter;
titleLabel.numberOfLines=0;
titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
titleLabel.textColor = [UIColor blackColor];
self.navigationItem.titleView = titleLabel;
}

Making variable size UILabel with maximum width

I made variable size UILabel with following code.
But I want to set maximum width to the label.
Do you have any idea?
- (void)viewDidLoad {
CGSize size = [self labelFrameWithString:#"test text"];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, size.width. size.height];
label.text = #"test text";
}
- (CGSize)labelFrameWithString:(NSString *)string {
CGRect frame = [string boundingRectWithSize:CGSizeZero
options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingTruncatesLastVisibleLine)
attributes:[NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:16] forKey:NSFontAttributeName]
context:nil];
return frame.size;
}
Have you try pass a constrained CGSize instead of CGSizeZero?
CGSize constraint = CGSizeMake(your_max_width ,NSUIntegerMax);
CGRect frame = [string boundingRectWithSize:constraint
options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingTruncatesLastVisibleLine)
attributes:[NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:16] forKey:NSFontAttributeName]
context:nil];

sizeWithFont:constrainedToSize - iOS7

I have the following method that I used in iOS6 but with iOS7 I'm getting errors on
CGSize labelHeight = [tweetText sizeWithFont:[UIFont systemFontOfSize:13.0f] constrainedToSize:CGSizeMake(self.tweetsTableView.bounds.size.width - 84, 4000)];
full method below, any ideas on how to amend for iOS7?
- (CGFloat)heightForCellAtIndex:(NSUInteger)index {
NSDictionary *tweet = self.tweets[index];
CGFloat cellHeight = 50;
NSString *tweetText = tweet[#"text"];
CGSize labelHeight = [tweetText sizeWithFont:[UIFont systemFontOfSize:13.0f] constrainedToSize:CGSizeMake(self.tweetsTableView.bounds.size.width - 84, 4000)];
cellHeight += labelHeight.height;
return cellHeight;
}
I know this is an old question & late answer, but it's still very relevant,
This sizeWithFont method is now deprecated, this new method works best
NSString *content = **Whatever your label's content is expected to be**
CGSize maximumLabelSize = CGSizeMake(390, 1000);
NSDictionary *stringAttributes = [NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:13] forKey: NSFontAttributeName];
CGSize newExpectedLabelSize = [content boundingRectWithSize:maximumLabelSize options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin attributes:stringAttributes context:nil].size;
So you can adjust your label (or table cell etc) to
label.frame.size.height = newExpectedLabelSize.height;
I hope this helps, cheers, Jim.
Add this lines:
UIFont *font = [UIFont boldSystemFontOfSize:16];
CGRect new = [string boundingRectWithSize:CGSizeMake(200, 300) options:NSStringDrawingUsesFontLeading attributes:#{NSFontAttributeName: font} context:nil];
CGSize stringSize= new.size;

Resize UILabel with sizeWithFont:constrainedToSize:lineBreakMode: deprecated in iOS7

If the sizeWithFont:constrainedToSize:lineBreakMode: method is deprecated in iOS7, how can I automatically resize a UILabel to dynamically adjust its height and width to fit the text?
I ended up using this. Works for me. This does not work with IBOutlets object but useful when computing dynamically the height of the text on uitableview's heightForRowAtIndexPath: method.
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont fontWithName:#"FontName" size:15], NSFontAttributeName,
nil];
CGRect frame = [label.text boundingRectWithSize:CGSizeMake(263, 2000.0)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributesDictionary
context:nil];
CGSize size = frame.size;
This should work in iOS6 and iOS7, but will break your label constraints (you need to set them all back programatically if needed):
-(void)resizeHeightForLabel: (UILabel*)label {
label.numberOfLines = 0;
UIView *superview = label.superview;
[label removeFromSuperview];
[label removeConstraints:label.constraints];
CGRect labelFrame = label.frame;
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
CGRect expectedFrame = [label.text boundingRectWithSize:CGSizeMake(label.frame.size.width, 9999)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:[NSDictionary dictionaryWithObjectsAndKeys:
label.font, NSFontAttributeName,
nil]
context:nil];
labelFrame.size = expectedFrame.size;
labelFrame.size.height = ceil(labelFrame.size.height); //iOS7 is not rounding up to the nearest whole number
} else {
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
labelFrame.size = [label.text sizeWithFont:label.font
constrainedToSize:CGSizeMake(label.frame.size.width, 9999)
lineBreakMode:label.lineBreakMode];
#pragma GCC diagnostic warning "-Wdeprecated-declarations"
}
label.frame = labelFrame;
[superview addSubview:label];
}
Add this method to your viewController and use it like this:
[self resizeHeightForLabel:myLabel];
//set new constraints here if needed