I have a UILabel acting like a ticker so every 0.09 seconds the text is being changed, but when a space comes at the end of the label it is being trimmed, so it is looking like the ticker is lagging.
Here’s the code:
[self setTickerLabel: [ [UILabel alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - 40, self.view.bounds.size.width, 40)]];
[self.tickerLabel setFont:[UIFont fontWithName:#"Courier" size:TICKER_FONT_SIZE]];
self.text =[NSString stringWithFormat:#"%#",self.result];
self.tickerLabel.textAlignment = NSTextAlignmentRight;
[self.tickerLabel setText:self.text];
[self.tickerLabel setLineBreakMode:NSLineBreakByWordWrapping];
[NSTimer scheduledTimerWithTimeInterval:TICKER_RATE target:self selector: #selector(nudgeTicker:) userInfo:nil repeats:YES];
[self.view addSubview:self.tickerLabel];
The nudge Ticker method does the following:
NSString* firstLetter = [self.text substringWithRange: NSMakeRange(0,1)];
NSString* remainder = [self.text substringWithRange:NSMakeRange(1,[self.text length]-1)];
self.text=[remainder stringByAppendingString: firstLetter];
self.tickerLabel.text=self.text;
I really need some help. How can I fix this? By the way the text of the UILabel is in Arabic.
A bit of a hack, but one solution would be to use an attributed string in your label and include a transparent period (".") at the end of the string.
Just replace your nudgeTicker: method.
- (void)nudgeTicker:(id)target {
NSString* firstLetter = [self.text substringWithRange: NSMakeRange(0,1)];
NSString* remainder = [self.text substringWithRange:NSMakeRange(1,[self.text length]-1)];
self.text=[remainder stringByAppendingString: firstLetter];
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:#"%#.", self.text]];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0,string.length-1)];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor clearColor] range:NSMakeRange(string.length-1,1)];
self.tickerLabel.attributedText = string;
}
Related
I have a UITextView and there are certain words I'm casting with NSString stringWithFormat that I'd like to be bolded.
I have looked around Stack Overflow and tried to follow the the postings but I guess I'm not understanding it.
Here's what I've been playing around with:
NSRange boldedRange = NSMakeRange(0, 4);
NSString *boldFontName = [[UIFont fontWithName:#"Helvetica-Bold" size:100]fontName];
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:self.name];
[attrString beginEditing];
[attrString addAttribute:NSFontAttributeName
value:boldFontName
range:boldedRange];
[attrString endEditing];
self.resultsTextView.attributedText = attrString;
self.resultsTextView.text = [NSString stringWithFormat:#"One day, %# was taking a walk and saw a %# boy. He was %# a %#.", attrString, self.adjective, self.adverb, self.noun];
You can also set it the following way if you want by setting a dictionary as a whole, as attribute
NSString *strTextView = #"This is some demo Text to set BOLD";
NSRange rangeBold = [strTextView rangeOfString:#"BOLD"];
UIFont *fontText = [UIFont boldSystemFontOfSize:10];
NSDictionary *dictBoldText = [NSDictionary dictionaryWithObjectsAndKeys:fontText, NSFontAttributeName, nil];
NSMutableAttributedString *mutAttrTextViewString = [[NSMutableAttributedString alloc] initWithString:strTextView];
[mutAttrTextViewString setAttributes:dictBoldText range:rangeBold];
[textViewTermsPolicy setAttributedText:mutAttrTextViewString];
Use the below code to set Attribute string in TextView.
NSString *infoString =#"I am Kirit Modi from Deesa.";
NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:infoString];
UIFont *font_regular=[UIFont fontWithName:#"Helvetica" size:20.0f];
UIFont *font_bold=[UIFont fontWithName:#"Helvetica-Bold" size:20.0f];
[attString addAttribute:NSFontAttributeName value:font_regular range:NSMakeRange(0, 4)];
[attString addAttribute:NSFontAttributeName value:font_bold range:NSMakeRange(5, 15)];
[attString addAttribute:NSFontAttributeName value:font_regular range:NSMakeRange(16, infoString.length - 15 - 1)];
[self.txtView setAttributedText:attString];
OutPut :
Check out #CrazyYoghurt improvement on #Bbrame and #BenoitJadinon on this previous SO question 3586871
I've been using it for over a year and it works great. One limitation: I don't think you can bold multiple times the same string if it appears more than once in your original string. But you can probably expend the code to make it do so if you wish.
If you also need to filter some word from the UITextView and make it underline/change color of that particular text only then you can use the below code.
Here, I'm getting all the doc text in the Content string and filter some particular text that is in Hebrew language.
NSMutableAttributedString *aStr = [[NSMutableAttributedString alloc]initWithString:content attributes:nil];
[aStr addAttribute:NSLinkAttributeName value:#"http://www.apple.com" range:[content rangeOfString:#"מדיניות פרטיות"]];
[aStr addAttribute:NSLinkAttributeName value:#"http://www.google.com" range:[content rangeOfString:#"לינק"]];
textview.linkTextAttributes = #{NSUnderlineStyleAttributeName : #(NSUnderlineStyleSingle)};
textview.delegate = (id)self;
//...You can as per your custom color
[aStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:[content rangeOfString:#"מדיניות פרטיות"]];
[aStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:[content rangeOfString:#"לינק"]];
//Here You can also add the tap gesture on that text.
//Tap gesture
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(tappedTextView:)];
[textview addGestureRecognizer:tapRecognizer];
[textview setAttributedText:aStr];
textview.textAlignment=NSTextAlignmentRight;
//For getting the text location in the tap gesture
-(void)tappedTextView:(UITapGestureRecognizer *)tapGesture
{
UITextView *textView = (UITextView *)tapGesture.view;
CGPoint tapLocation = [tapGesture locationInView:textView];
UITextPosition *textPosition = [textView closestPositionToPoint:tapLocation];
NSDictionary *attributes = [textView textStylingAtPosition:textPosition inDirection:UITextStorageDirectionForward];
NSString *urlStr = attributes[NSLinkAttributeName];
if (urlStr)
{
//[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#",url]]];
PrivacyViewController *next = [PrivacyViewController new];
[self.navigationController pushViewController:next animated:YES];
}
}
I have read several method about bolding a part of string.
But I still can't get it work.
Here's my code
#define FONT_OPEN_BOLD(s) [UIFont fontWithName:#"OpenSans-Bold" size:s]
In viewDidLoad function
NSString *stringName = #"ShowTimes" ;
UIFont *font = FONT_OPEN_BOLD(15.0f);
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:stringName];
[attrString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, 4)];
self.title = stringName;
Any suggestion?
Thank you in advance. ^^
NSString *stringName = #"ShowTimes" ;
UIFont *font = FONT_OPEN_BOLD(15.0f);
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:stringName];
[attrString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, 4)];
//Initialize TTAttributedLabel with rect
UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 20, 150)];
//Set the attributedText property of TTAttributedLabel
label.attributedText = attrString;
//Set navigationItem.titleView to the label view we've created
self.navigationItem.titleView = label;
What you could do is use an NSAttributedString.
NSString *boldFontName = [[UIFont boldSystemFontOfSize:12] fontName];
NSString *yourString = ...;
NSRange boldedRange = NSMakeRange(22, 4);
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:yourString];
[attrString beginEditing];
[attrString addAttribute:kCTFontAttributeName
value:boldFontName
range:boldedRange];
[attrString endEditing];
//draw attrString here...
Take a look at this handy dandy guide to drawing NSAttributedString objects with Core Text.
I need the text of a UILabel to be black, but have a light gray underline under the text. Is this possible with NSAttributedString or TTTAttributedLabel? Or is custom drawing using Core Graphics needed?
CLARIFICATION:
I need a specific color text on a different color underline. Example: blue text on red underline.
You can do with NSAttributedString as below.
NSMutableAttributedString* string = [[NSMutableAttributedString alloc]initWithString:#"you string"];
[string addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, string.length)];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, string.length)];//TextColor
[string addAttribute:NSUnderlineStyleAttributeName value:underlineNumber range:NSMakeRange(0, string.length)];//Underline color
[string addAttribute:NSUnderlineColorAttributeName value:[UIColor lightGrayColor] range:NSMakeRange(0, string.length)];//TextColor
yourlabel. attributedText = string;
Note: You can also underline particular range of string as like in this post. Also note down, it works ios6+ only.
Instead of creating a local NSMutableAttributedString and adding attributes one by one, we can always create multiple attributes in one single line (using NSDictionary symbols - # { } ) to a specific UILabel including the actual text.
Objective C:
[someUILabel setAttributedText:
[[NSAttributedString alloc] initWithString:[NSString stringWithFormat:#"%#", [someObject stringProperty]]
attributes:#{NSUnderlineStyleAttributeName:#(NSUnderlineStyleThick),
NSUnderlineColorAttributeName:[[UIColor alloc] initWithRed:0.953f green:0.424f blue:0.416f alpha:1.00f]}]];
In the above example we have set an underline which is also bold - total 2 attributes.
Swift:
self.someUIButton.setAttributedTitle(NSAttributedString(string: "UIButtonStringTitle", attributes: [NSUnderlineStyleAttributeName : 1]), forState: .Normal)
// Print `str` in black, and underline the word STRING in gray.
NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:#"This is my STRING"];
[str addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, str.length-7)];
[str addAttribute:NSUnderlineColorAttributeName value:[UIColor grayColor] range:NSMakeRange([str length]-6, 6)];
[str addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:NSUnderlineStyleSingle] range:NSMakeRange([str length]-6, 6)];
_label.attributedText = str; // assuming you have an iVar name `label`
NSAttributedString *title;
title = [[NSAttributedString alloc] initWithString:#"iphone app" for NSAttributedString" attributes:#{ NSFontAttributeName : [UIFont fontWithName:#"Noteworthy-Bold" size:36], NSUnderlineStyleAttributeName : #1 , NSStrokeColorAttributeName : [UIColor blackColor]}];
UILabel *label;
label = [[UILabel alloc] initWithFrame:CGRectMake( (self.view.bounds.size.width - title.size.width) / 2.0f, 40.0f, title.size.width, title.size.height)];
label.attributedText = title;
[self.view addSubview:label];
m-farhan.com farhan will be underlined
//-----------------------------
// Create attributed string
//-----------------------------
NSString *str = #"m-Farhan.com";
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:str];
// Add attribute NSUnderlineStyleAttributeName
[attributedString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:NSUnderlineStyleSingle] range:NSMakeRange(2, 4)];
// Set background color for entire range
[attributedString addAttribute:NSBackgroundColorAttributeName
value:[UIColor colorWithRed:0.103 green:0.305 blue:0.492 alpha:1.000]
range:NSMakeRange(0, [attributedString length])];
// Define label
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 20, 280, 80)];
[label setLineBreakMode:UILineBreakModeWordWrap];
[label setTextColor:[UIColor whiteColor]];
[label setBackgroundColor:[UIColor clearColor]];
[label setTextAlignment:UITextAlignmentLeft];
// Set label text to attributed string
[label setAttributedText:attributedString];
[[self view] addSubview:label];
In swift, use NSAttributedString.Key.underlineColor.
I know there are many links to get the height of the label within the cell. I have tried every thing .. nothing is working ..
My scenario is :
I have a cell , in this cell i have 6 labels , text within these labels are dynamic and coming from a web service.
I dont know what i am doing wrong , i have applied every thing to get the dynamic height right:
i have 2 issues:
1) when tableview loads first time heights of labels are not proper (its according to nib).
2) when i reload table view it gives me the dynamic height , but its not correct.
here is my code:
In controller where i am calculating to height of cell each time :
-(float)saltDetailsCellHeight : (HKDrugSaltInfoModel *)saltInfoModel
{
UIColor *_black=[UIColor blackColor];
UIColor *_lightGray = [UIColor lightGrayColor];
UIFont *font=[UIFont fontWithName:#"HelveticaNeue" size:13.0f];
// salt Heading
NSString * saltNameLabelString = [NSString stringWithFormat:#"%# %#",saltInfoModel.saltName,saltInfoModel.strength];
float hSaltNameLabelString = [HKGlobal heightOfGivenText:saltNameLabelString ofWidth:300.0 andFont:font];
// Salts string
NSString * saltsString = [NSString stringWithFormat:#"Pregnancy:%# Lactation:%# Lab:%# Food:%#",saltInfoModel.ci_pg,
saltInfoModel.ci_lc,saltInfoModel.ci_lb,saltInfoModel.ci_fd];
float hSaltsString = [HKGlobal heightOfGivenText:saltsString ofWidth:300.0 andFont:font];
// Usage Label
NSString *usageString = [NSString stringWithFormat:#"Typical Usage: %#",saltInfoModel.lc];
NSMutableAttributedString* attrStr = [[NSMutableAttributedString alloc] initWithString:usageString];
NSInteger _stringLength=[usageString length];
[attrStr addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, _stringLength)];
[attrStr addAttribute:NSForegroundColorAttributeName value:_black range:NSMakeRange(0, 14)];
[attrStr addAttribute:NSForegroundColorAttributeName value:_lightGray range:NSMakeRange(15, _stringLength-15)];
float hUsageString = [HKGlobal heightOfGivenText:[NSString stringWithFormat:#"%#", (NSString *)attrStr] ofWidth:300.0 andFont:font];
// Side Effects label
NSString *sideEffectsString = [NSString stringWithFormat:#"Side Effects: %#",saltInfoModel.se];
NSMutableAttributedString* attrStrSide = [[NSMutableAttributedString alloc] initWithString:sideEffectsString];
NSInteger _stringLengthSE = [sideEffectsString length];
[attrStrSide addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, _stringLengthSE)];
[attrStrSide addAttribute:NSForegroundColorAttributeName value:_black range:NSMakeRange(0, 14)];
[attrStrSide addAttribute:NSForegroundColorAttributeName value:_lightGray range:NSMakeRange(15, _stringLengthSE-15)];
float hSideEffectsString = [HKGlobal heightOfGivenText:[NSString stringWithFormat:#"%#",(NSString *)attrStrSide] ofWidth:300.0 andFont:font];
// Drug Interaction Label
NSString *drugInteractionString = [NSString stringWithFormat:#"Drug Interaction: %#",saltInfoModel.di];
NSMutableAttributedString* attrdrugInteractionStr = [[NSMutableAttributedString alloc] initWithString:drugInteractionString];
NSInteger _strLenDrugInteraction = [drugInteractionString length];
[attrdrugInteractionStr addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, _strLenDrugInteraction)];
[attrdrugInteractionStr addAttribute:NSForegroundColorAttributeName value:_black range:NSMakeRange(0, 18)];
[attrdrugInteractionStr addAttribute:NSForegroundColorAttributeName value:_lightGray range:NSMakeRange(18, _strLenDrugInteraction-18)];
float hAttrdrugInteractionStr = [HKGlobal heightOfGivenText:[NSString stringWithFormat:#"%#", (NSString*)attrdrugInteractionStr] ofWidth:300.0 andFont:font];
// MechanismOfAction Label
NSString *moaString = [NSString stringWithFormat:#"Mechanism Of Action: %#",saltInfoModel.moa];
NSMutableAttributedString* attrMoaStr = [[NSMutableAttributedString alloc] initWithString:moaString];
NSInteger _strLenMoa=[moaString length];
[attrMoaStr addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, _strLenMoa)];
[attrMoaStr addAttribute:NSForegroundColorAttributeName value:_black range:NSMakeRange(0, 21)];
[attrMoaStr addAttribute:NSForegroundColorAttributeName value:_lightGray range:NSMakeRange(21, _strLenMoa-21)];
float hAttrMoaStr = [HKGlobal heightOfGivenText:[NSString stringWithFormat:#"%#", (NSString*)attrMoaStr] ofWidth:300.0 andFont:font];
arrayOFLabelsHeights = [[NSMutableArray alloc] initWithObjects:[NSNumber numberWithFloat:hSaltNameLabelString],
[NSNumber numberWithFloat:hSaltsString],
[NSNumber numberWithFloat:hUsageString],
[NSNumber numberWithFloat:hSideEffectsString],
[NSNumber numberWithFloat:hAttrdrugInteractionStr],
[NSNumber numberWithFloat:hAttrMoaStr],
nil];
float cellHeight = hSaltNameLabelString+10+hSaltsString+10+hUsageString+10+hSideEffectsString+10+hAttrdrugInteractionStr+10+hAttrMoaStr;
return cellHeight;
}
and i am using above method in tableview:heightForRowAtIndexpath:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return [self saltDetailsCellHeight:[self.drugDetailModel.saltInfoArray objectAtIndex:indexPath.row-3]];
}
And in cell for row at index path i am PASSSing the arrayOFLabelsHeights array , which contains the height of each label :
HKMedicineDetailInfoCell *medicineDetailInfoCell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier2];
if(medicineDetailInfoCell == nil)
{
medicineDetailInfoCell = (HKMedicineDetailInfoCell *)[[[NSBundle mainBundle] loadNibNamed:#"MedicineDetailInfoCell" owner:self options:nil] objectAtIndex:0];
}
//Check whether array contains any object or not
if([self.drugDetailModel.saltInfoArray count] > 0)
{
[medicineDetailInfoCell customiseLabels:[self.drugDetailModel.saltInfoArray objectAtIndex:indexPath.row-3] WithHeights:arrayOFLabelsHeights]; // since 3 rows are already there
}
return medicineDetailInfoCell;
And the method customiseLabels: is declared in my custom cell class like this (i think there would be code duplicacy but i have to do this, not able to find any other way):
-(void)customiseLabels:(HKDrugSaltInfoModel *)saltInfoModel WithHeights:(NSArray *)heightsArray
{
UIColor *_black=[UIColor blackColor];
UIColor *_lightGray = [UIColor lightGrayColor];
//Helvetica Neue
UIFont *font=[UIFont fontWithName:#"HelveticaNeue" size:13.0f];
float h1 = [[heightsArray objectAtIndex:0] floatValue];
frameTemp = self.saltNameLabel.frame;
frameTemp.size.height = h1;
self.saltNameLabel.frame = frameTemp;
self.saltNameLabel.text = [NSString stringWithFormat:#"%# %#",saltInfoModel.saltName,saltInfoModel.strength];
frameTemp.origin.y += h1+10;
float h2 = [[heightsArray objectAtIndex:1] floatValue];
frameTemp.size.height = h2;
self.secondDescriptiveLabel.frame = frameTemp;
self.secondDescriptiveLabel.text = [NSString stringWithFormat:#"Pregnancy:%# Lactation:%# Lab:%# Food:%#",saltInfoModel.ci_pg,saltInfoModel.ci_lc,saltInfoModel.ci_lb,saltInfoModel.ci_fd];
frameTemp.origin.y += h2+10;
float h3 = [[heightsArray objectAtIndex:2] floatValue];
frameTemp.size.height = h3;
self.usageLabel.frame = frameTemp;
// Usage Label
NSString *str = [NSString stringWithFormat:#"Typical Usage: %#",saltInfoModel.lc];
NSMutableAttributedString* attrStr = [[NSMutableAttributedString alloc] initWithString:str];
NSInteger _stringLength=[str length];
[attrStr addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, _stringLength)];
[attrStr addAttribute:NSForegroundColorAttributeName value:_black range:NSMakeRange(0, 14)];
[attrStr addAttribute:NSForegroundColorAttributeName value:_lightGray range:NSMakeRange(15, _stringLength-15)];
self.usageLabel.attributedText = attrStr;
frameTemp.origin.y += h3+10;
float h4 = [[heightsArray objectAtIndex:3] floatValue];
frameTemp.size.height = h4;
self.sideEffectsLabel.frame = frameTemp;
// Side Effects label
NSString *sideEffectsString = [NSString stringWithFormat:#"Side Effects: %#",saltInfoModel.se];
NSMutableAttributedString* attrSideEffectsStr = [[NSMutableAttributedString alloc] initWithString:sideEffectsString];
NSInteger _strLenSideEffects=[sideEffectsString length];
[attrSideEffectsStr addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, _strLenSideEffects)];
[attrSideEffectsStr addAttribute:NSForegroundColorAttributeName value:_black range:NSMakeRange(0, 14)];
[attrSideEffectsStr addAttribute:NSForegroundColorAttributeName value:_lightGray range:NSMakeRange(14, _strLenSideEffects-14)];
self.sideEffectsLabel.attributedText = attrSideEffectsStr;
frameTemp.origin.y += h4+10;
float h5 = [[heightsArray objectAtIndex:4] floatValue];
frameTemp.size.height = h5;
self.drugInteractionLabel.frame = frameTemp;
// Drug Interaction Label
NSString *drugInteractionString = [NSString stringWithFormat:#"Drug Interaction: %#",saltInfoModel.di];
NSMutableAttributedString* attrdrugInteractionStr = [[NSMutableAttributedString alloc] initWithString:drugInteractionString];
NSInteger _strLenDrugInteraction=[drugInteractionString length];
[attrdrugInteractionStr addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, _strLenDrugInteraction)];
[attrdrugInteractionStr addAttribute:NSForegroundColorAttributeName value:_black range:NSMakeRange(0, 18)];
[attrdrugInteractionStr addAttribute:NSForegroundColorAttributeName value:_lightGray range:NSMakeRange(18, _strLenDrugInteraction-18)];
self.drugInteractionLabel.attributedText = attrdrugInteractionStr;
frameTemp.origin.y += h5+10;
float h6 = [[heightsArray objectAtIndex:5] floatValue];
frameTemp.size.height = h6;
self.moaLabel.frame = frameTemp;
// MechanismOfAction Label
NSString *moaString = [NSString stringWithFormat:#"Mechanism Of Action: %#",saltInfoModel.moa];
NSMutableAttributedString* attrMoaStr = [[NSMutableAttributedString alloc] initWithString:moaString];
NSInteger _strLenMoa=[moaString length];
[attrMoaStr addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, _strLenMoa)];
[attrMoaStr addAttribute:NSForegroundColorAttributeName value:_black range:NSMakeRange(0, 21)];
[attrMoaStr addAttribute:NSForegroundColorAttributeName value:_lightGray range:NSMakeRange(21, _strLenMoa-21)];
self.moaLabel.attributedText = attrMoaStr;
NSLog(#"height of cell : %f", frameTemp.origin.y + self.moaLabel.frame.size.height);
}
Still i have large spaces in between labels , here is screenshot:
I have tried every thing .. and struggling with this issue for many hours (a small issue i think :( )
I do not see where you are setting the height of the cell. You should not call some obscure function in heightForRowAtIndexPath but return the height of the cell.
Ask your datasource for the necessary strings and then calculate the height the usual way, i.e. using boundingRectWithSize:options:attributes:context:. The source of your problem is the convoluted code.
Can I set the attributedText property of a UILabel object? I tried the below code:
UILabel *label = [[UILabel alloc] init];
label.attributedText = #"asdf";
But it gives this error:
Property "attributedText" not found on object of type 'UILabel *'
#import <CoreText/CoreText.h> not working
Here is a complete example of how to use an attributed text on a label:
NSString *redText = #"red text";
NSString *greenText = #"green text";
NSString *purpleBoldText = #"purple bold text";
NSString *text = [NSString stringWithFormat:#"Here are %#, %# and %#",
redText,
greenText,
purpleBoldText];
// If attributed text is supported (iOS6+)
if ([self.label respondsToSelector:#selector(setAttributedText:)]) {
// Define general attributes for the entire text
NSDictionary *attribs = #{
NSForegroundColorAttributeName: self.label.textColor,
NSFontAttributeName: self.label.font
};
NSMutableAttributedString *attributedText =
[[NSMutableAttributedString alloc] initWithString:text
attributes:attribs];
// Red text attributes
UIColor *redColor = [UIColor redColor];
NSRange redTextRange = [text rangeOfString:redText];// * Notice that usage of rangeOfString in this case may cause some bugs - I use it here only for demonstration
[attributedText setAttributes:#{NSForegroundColorAttributeName:redColor}
range:redTextRange];
// Green text attributes
UIColor *greenColor = [UIColor greenColor];
NSRange greenTextRange = [text rangeOfString:greenText];// * Notice that usage of rangeOfString in this case may cause some bugs - I use it here only for demonstration
[attributedText setAttributes:#{NSForegroundColorAttributeName:greenColor}
range:greenTextRange];
// Purple and bold text attributes
UIColor *purpleColor = [UIColor purpleColor];
UIFont *boldFont = [UIFont boldSystemFontOfSize:self.label.font.pointSize];
NSRange purpleBoldTextRange = [text rangeOfString:purpleBoldText];// * Notice that usage of rangeOfString in this case may cause some bugs - I use it here only for demonstration
[attributedText setAttributes:#{NSForegroundColorAttributeName:purpleColor,
NSFontAttributeName:boldFont}
range:purpleBoldTextRange];
self.label.attributedText = attributedText;
}
// If attributed text is NOT supported (iOS5-)
else {
self.label.text = text;
}
Unfortunately, UILabel doesn't support attributed strings. You can use OHAttributedLabel instead.
Update: Since iOS6, UILabel does support attributed strings. See UILabel reference or Michael Kessler's answer below for more details.
NSString *str1 = #"Hi Hello, this is plain text in red";
NSString *cardName = #"This is bold text in blue";
NSString *text = [NSString stringWithFormat:#"%#\n%#",str1,cardName];
// Define general attributes for the entire text
NSDictionary *attribs = #{
NSForegroundColorAttributeName:[UIColor redColor],
NSFontAttributeName: [UIFont fontWithName:#"Helvetica" size:12]
};
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:text attributes:attribs];
UIFont *boldFont = [UIFont fontWithName:#"Helvetica-Bold" size:14.0];
NSRange range = [text rangeOfString:cardName];
[attributedText setAttributes:#{NSForegroundColorAttributeName: [UIColor blueColor],
NSFontAttributeName:boldFont} range:range];
myLabel = [[UILabel alloc] initWithFrame:CGRectZero];
myLabel.attributedText = attributedText;
for Swift 4:
iOS 11 and xcode 9.4
let str = "This is a string which will shortly be modified into AtrributedString"
var attStr = NSMutableAttributedString.init(string: str)
attStr.addAttribute(.font,
value: UIFont.init(name: "AppleSDGothicNeo-Bold", size: 15) ?? "font not found",
range: NSRange.init(location: 0, length: str.count))
self.textLabel.attributedText = attStr
For people using swift, here's a one-liner:
myLabel.attributedText = NSMutableAttributedString(string: myLabel.text!, attributes: [NSFontAttributeName:UIFont(name: "YourFont", size: 12), NSForegroundColorAttributeName: UIColor.whiteColor()])
so,here is the code to have different properties for sub strings ,of a string.
NSString *str=#"10 people likes this";
NSString *str2=#"likes this";
if ([str hasSuffix:str2])
{
NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:str];
// for string 1 //
[string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0,str.length-str2.length)];
[string addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:14] range:NSMakeRange(0,str.length-str2.length)];
// for string 2 //
[string addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange((str.length-str2.length),str2.length)];
[string addAttribute:NSFontAttributeName value:[UIFont italicSystemFontOfSize:12] range:NSMakeRange((str.length-str2.length),str2.length)];
label.attributedText=string;
}
else
{
label.text =str;
}
Hope this helps ;)
NSMutableAttributedString* attrStr = [NSMutableAttributedString attributedStringWithString:#"asdf"];
[attrStr setFont:[UIFont systemFontOfSize:12]];
[attrStr setTextColor:[UIColor grayColor]];
[attrStr setTextColor:[UIColor redColor] range:NSMakeRange(0,5)];
lbl.attributedText = attrStr;
UIFont *font = [UIFont boldSystemFontOfSize:12];
NSDictionary *fontDict = [NSDictionary dictionaryWithObject: font forKey:NSFontAttributeName];
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:#" v 1.2.55" attributes: fontDict];
UIFont *fontNew = [UIFont boldSystemFontOfSize:17];
NSDictionary *fontDictNew = [NSDictionary dictionaryWithObject: fontNew forKey:NSFontAttributeName];
NSMutableAttributedString *attrStringNew = [[NSMutableAttributedString alloc] initWithString:#“Application” attributes: fontDictNew];
[attrStringNew appendAttributedString: attrString];
self.vsersionLabel.attributedText = attrStringNew;