iOS - Auto-shrink UILabel with Attributed text - iphone

I have UILabel which contains two attributed strings separated by a new line.
FIrst string has font size set to 17 and the second one to 14.
I want my first NSMutableAttributedString be resized to minimum font size if its content can't fit in a single line.
Is that possible?
It is pretty simple to configure such UILabel behaviour by setting "auto shrink to minimum font size" in IB for plain text, but don't know how to do it for attributed text.
Here is my code:
NSString *eventName = #"Looong Event Name";
NSString *placeString = #"My place";
eventName = [eventName stringByAppendingString:#"\n"];
NSMutableAttributedString *attrName = [[NSMutableAttributedString alloc] initWithString:eventName];
[attrName addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:17] range:NSMakeRange(0, [eventName length])];
NSMutableAttributedString *attrPlace = [[NSMutableAttributedString alloc] initWithString:placeString];
[attrPlace addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14] range:NSMakeRange(0, placeString.length)];
[attrPlace addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, placeString.length)];
NSMutableAttributedString *finalString = [[NSMutableAttributedString alloc] initWithAttributedString:attrName];
[finalString appendAttributedString:attrPlace];
UILabel *nameLabel = (UILabel *)[cell viewWithTag:100];
nameLabel.attributedText = finalString;

I guess this is a follow on from your earlier question.
I don't think you can do this automatically, but there is a size method of NSAttributedString which you can use to check if your string is too big, and adjust yourself if required.

Related

UILabel is not displaying its correct value even if it is giving the newly assigned value in console

I have a UILabel which is displayed as a question. Its successfully displaying the question text which has been assigned to it programmatically. But later according to one if else condition, I have to change text in the label.Specifically I want to display an asterik(*) mark at the end of the string if that is a mandatory question.The * should be in red color and rest of the text should be in black.But it displays only the question not the * mark.If I try to print the questLabel.text it is giving the question with * mark at the end.Here is the code that I am trying
questText = questLabel.text;
questText = [questText stringByAppendingString:#"✶"];
NSMutableAttributedString * str = [[NSMutableAttributedString alloc] initWithString:questText];
NSMutableAttributedString *text =
[[NSMutableAttributedString alloc]
initWithAttributedString: str];
int length = (int)text.length;
[text addAttribute:NSForegroundColorAttributeName
value:[UIColor redColor]
range:NSMakeRange(length-1, 1)];
[questLabel setAttributedText: text];
If I try to print the value of questLabel.attributedText :
Question{
}✶{
NSColor = "UIDeviceRGBColorSpace 1 0 0 1";
}
And the value for questLabel.text is :Question✶
Please help me out with this..Thanks in advance..
You should change your code to this.
NSString *questText = questLabel.text;
questText = [questText stringByAppendingString:#"✶"];
NSMutableAttributedString *text =
[[NSMutableAttributedString alloc] initWithString:questText];
int length = (int)text.length;
[text addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, length-1)];
[text addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(length-1, 1)];
[questLabel setAttributedText: text];
You can also try this
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:self.questLabel.text attributes:#{NSForegroundColorAttributeName:[UIColor blackColor]}];
NSMutableAttributedString *starString = [[NSMutableAttributedString alloc] initWithString:#"✶" attributes:#{NSForegroundColorAttributeName:[UIColor redColor]}];
[string appendAttributedString:starString];
[self.questLabel setAttributedText:string];

Letter spacing in IOS 6

I would like to know that how can i set Letter spacing in iOS 6? It's working fine for iOS 7 using below code, now need to do for iOS 6 :
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:[arraySettings objectAtIndex:indexPath.row]];
float spacing = 0.2f;
[attributedString addAttribute:NSKernAttributeName
value:#(spacing)
range:NSMakeRange(0, [[arraySettings objectAtIndex:indexPath.row] length])];
cell.textLabel.attributedText = attributedString;
error image after crashing above code in iOS 6 :
Thanks.
My guess is that you have some sort of memory related issue with your arraySettings ivar.
I've slightly modified the code you provided in a test project and it seemed to work fine for me when run on both the iOS 6.1 and 7.1 simulator.
Could you try using the following code and see what happens?
NSString *string = [[arraySettings objectAtIndex:indexPath.row] copy];
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string];
CGFloat spacing = 0.2f;
[attributedString addAttribute:NSKernAttributeName value:#(spacing) range:NSMakeRange(0, string.length)];
cell.textLabel.attributedText = attributedString;
If you are still getting a crash then you will need to provide more info about what you are doing with the arraySettings object.
I had to do same thing in one of my project and used this same code. It was working fine for me.
NSMutableAttributedString *attributedString =
[[NSMutableAttributedString alloc] initWithString:#"hi this is my testing string"];
float spacing = 1.0f;
[attributedString addAttribute:NSKernAttributeName
value:#(spacing)
range:NSMakeRange(0, [#"hi this is my testing string" length])];
mylbl.attributedText = attributedString;

Make the specific string Pattern bold and blue in UILable

i have a program in which i get a tweets from twitter and show them in UITableviewcell. now problem is that i have to make a all twitter names bold and bule and show them in the orginal tweet with bule and bold names.
For Example i have tweet like this
MT #OraTV: SNEAK PEEK: #tomgreenlive #TheoVon & #DavidBegnaud talk Miley's #twerking #Batfleck &more on
so all the names starting with # should be bold and bule.
i use this code to extract All names starting with # but not know how to bold them and show
them in single uitableviewcell
NSString * aString =twitterMessage
NSMutableArray *substrings = [NSMutableArray new];
NSScanner *scanner = [NSScanner scannerWithString:aString];
[scanner scanUpToString:#"#" intoString:nil];
while(![scanner isAtEnd]) {
NSString *substring = nil;
[scanner scanString:#"#" intoString:nil];
if([scanner scanUpToString:#" " intoString:&substring]) {
[substrings addObject:substring];
}
[scanner scanUpToString:#"#" intoString:nil];
}
you have to build an NSAttributedString by swiping between 2 fonts and colors.
If you're able to detect them, you should probably replace your names by surrounding them with a known markup (eg: #aName). Then, parse the string to build a NSAttributedString.
You can use this code (not tested, you'll probably have to tweak):
// String to parse
NSString *markup = #"MT <color>#OraTV</color>: SNEAK PEEK: <color>#tomgreenlive</color>...";
// Names font and color
UIFont *boldFont = [UIFont boldSystemFontOfSize:15.0f];
UIColor *boldColor = [UIColor blueColor];
// Other text font and color
UIFont *stdFont = [UIFont systemFontOfSize:15.0f];
UIColor *stdColor = [UIColor blackColor];
// Current font and color
UIFont *currentFont = stdFont;
UIColor *currentColor = stdColor;
// Parse HTML string
NSMutableAttributedString *aString = [[NSMutableAttributedString alloc] initWithString:#""];
NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:#"(.*?)(<[^>]+>|\\Z)"
options:NSRegularExpressionCaseInsensitive|NSRegularExpressionDotMatchesLineSeparators
error:nil];
NSArray *chunks = [regex matchesInString:markup options:0 range:NSMakeRange(0, [markup length])];
for (NSTextCheckingResult* b in chunks)
{
NSArray *parts = [[markup substringWithRange:b.range] componentsSeparatedByString:#"<"];
NSDictionary *attrs = [NSDictionary dictionaryWithObjectsAndKeys:currentFont,NSFontAttributeName,currentColor,NSForegroundColorAttributeName,nil];
[aString appendAttributedString:[[NSAttributedString alloc] initWithString:[parts objectAtIndex:0] attributes:attrs]];
if([parts count] > 1)
{
NSString *tag = (NSString *)[parts objectAtIndex:1];
if([tag hasPrefix:#"color"])
{
currentFont = boldFont;
currentColor = boldColor;
}
else if([tag hasPrefix:#"/color"])
{
currentFont = stdFont;
currentColor = stdColor;
}
}
}
Hope that helps.
Cyril
So you have all the names properly extracted already? If so, it seems like NSAttributedString is what you want. More information here.
Something like this: [str setTextColor:[UIColor blueColor] range:NSMakeRange(0,5)];
For bold text, use [UIFont boldSystemFontOfSize:fontSize]. See example in the second link above.

Combining Attributed Strings

As an example, say I had an array of 10 NSAttributedStrings, what is the best method for combining them all into one string? I know of the appendAttributedString method, but this only allows for one to be combined at a time, meaning a loop is needed.
Or is there any need to combine them if theyre just going into a textview - just have a loop to add them to that view? Im just trying to get my head around how a lot of text in different formats is added to a textview!
Please, try:
NSRange range = NSMakeRange(0, 1);
NSString *space = #" ";
NSMutableAttributedString *attSpace = [[NSMutableAttributedString alloc] initWithString:space];
[attSpace addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:range];
[attSpace addAttribute:NSFontAttributeName value:[UIFont fontWithName:#"HelveticaNeue-Light"
size:11.f] range:range];
range = NSMakeRange(0, [string1 length]);
NSMutableAttributedString *att1 = [[NSMutableAttributedString alloc] initWithString:string1];
[att1 addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:range];
[att1 addAttribute:NSFontAttributeName value:[UIFont fontWithName:#"HelveticaNeue-Light"
size:11.f] range:range];
range = NSMakeRange(0, [string2 length]);
NSMutableAttributedString *att2 = [[NSMutableAttributedString alloc] initWithString:string2];
[att2 addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:range];
[att2 addAttribute:NSFontAttributeName value:[UIFont fontWithName:#"HelveticaNeue-Light"
size:11.f] range:range];
[att1 appendAttributedString:attSpace];
[att1 appendAttributedString:att2];
I'll share a kind of complex combination I've made mixing plain, striked and bold text in a resultant attributed string over the title of UIButton.
// Monthly button
NSMutableAttributedString *strikedOutPrice = [[NSMutableAttributedString alloc] initWithString:#"6,99"];
[strikedOutPrice setAttributes:#{ NSForegroundColorAttributeName : [UIColor whiteColor], NSStrikethroughStyleAttributeName: #2 } range:NSMakeRange(0, [strikedOutPrice length])];
NSMutableAttributedString *boldPrice = [[NSMutableAttributedString alloc] initWithString:#"4,99"];
[boldPrice setAttributes:#{ NSFontAttributeName:[UIFont boldSystemFontOfSize:16.0f], NSForegroundColorAttributeName : [UIColor whiteColor] } range:NSMakeRange(0, [boldPrice length])];
NSMutableAttributedString* titleStringMonthly = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:#"%# %# %#" , [[LocalizationSystem sharedLocalSystem] localizedStringForKey:#"1 Month for" value:#"1 Mes por"], #"6,99", #"4,99"]];
[titleStringMonthly setAttributes:#{ NSForegroundColorAttributeName : [UIColor whiteColor] } range:NSMakeRange(0, [titleStringMonthly length])];
NSString *language = [Utils getAppLanguage];
if([language isEqualToString:#"es"])
{
[titleStringMonthly replaceCharactersInRange:NSMakeRange(10, 4) withAttributedString:strikedOutPrice];
[titleStringMonthly replaceCharactersInRange:NSMakeRange(15, 4) withAttributedString:boldPrice];
}
else
{
[titleStringMonthly replaceCharactersInRange:NSMakeRange(12, 4) withAttributedString:strikedOutPrice];
[titleStringMonthly replaceCharactersInRange:NSMakeRange(17, 4) withAttributedString:boldPrice];
}
[_oneMonthButton setAttributedTitle:titleStringMonthly forState:UIControlStateNormal];
I imagine that for this case you could have a couple of dynamic counters that keeps track of the index and length of the next range and make the replacements over a NSMutableAttributedString (like I do with my titleStringMonthly on the example)
Hope It helps someone.
You could do something like this
NSString *attr = [NSString stringWithFormat:#"%#%#%#", attributedString1, string2, string3];
Doing so will result in one attr string variable with all 10 of the strings put together, and you could do [textView setText:attr]; :)

How to add UILabel between two strings

i have this code to show some texts in a UITextview..i just want to add a UILabel between these strings.i am getting text in this formate, 1 this is first text 2 this is second text 3 this is third text,,i want to add or append UILabel between numeric character and text.my code for showing text is
NSMutableString *combined = [NSMutableString string];
for(NSUInteger idx = 0; idx < [delegatee.allSelectedVerseEnglish count]; idx++) {
[combined appendFormat:#" %d %#",
idx + 1,
[delegatee.allSelectedVerseEnglish objectAtIndex:idx]];
}
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
NSNumber * n = [f numberFromString:combined];
NSLog(#"N: %#", n);
maintextview.text =combined;
combined is the text in the above formate ,and maintextview is the UITextview.
am also getting the string range between two sentence
- (void)textViewDidEndEditing:(UITextView *)textView
{
if (textView == maintextview) {
mainpopupview.frame =CGRectMake(0, 0, 768, 1004) ;
[self.view addSubview:mainpopupview];
NSRange selectedRange = [textView selectedRange];
NSString *backString = [maintextview.text substringToIndex:selectedRange.location];
NSRange backRange = [backString rangeOfString:#" " options:NSBackwardsSearch];
NSRange backRangee = [backString rangeOfString:#" " options:NSBackwardsSearch];
int myRangeLenght = backRangee.location - backRange.location;
NSRange myStringRange = NSMakeRange (backRange.location, myRangeLenght);
NSString *forwardString = [maintextview.text substringFromIndex:backRange.location];
NSLog(#"%#",[[forwardString componentsSeparatedByString:#" "] objectAtIndex:1]);
NSLog (#"%#", [maintextview.text substringWithRange:myStringRange]);
NSString * myStringTxt = [[forwardString componentsSeparatedByString:#" "] objectAtIndex:1];
NSLog(#"1 %#", myStringTxt);
// maintextview.textColor = [UIColor yellowColor];
NSRange myStringRangee = [maintextview.text rangeOfString:myStringTxt];
[maintextview select:self];
maintextview.selectedRange = myStringRangee;
is there any way to do this.
Thanks in advance.
I don't know what user interaction you need here, but if you're just displaying the text for the user, but could you replace your UITextView with a UIWebView (loading static text via loadHTMLString:baseURL:, using html markup to set the color of the text)? I refer to the UITextView documentation:
This class does not support multiple styles for text. The font, color,
and text alignment attributes you specify always apply to the entire
contents of the text view. To display more complex styling in your
application, you need to use a UIWebView object and render your
content using HTML.
If you really need to do this with separate UI controls (much more complicated than just using a UIWebView) you don't "insert" the UILabel in the text, but rather you'd probably have one control for the text up to the point of the color change, another control for the text of a different color or what have you, another control for the rest of the text. It would get hairly pretty quickly (unless it was laid out like a grid, and even then it's a hassle compared to a UIWebView).