iOS: Truncate a large string , and appending a suffix string - ios

I need to display some text in two lines , e.g.
| a very large string string string |
| string string ... - a suffix string |
The whole text contains two part
a large description string, need be truncated
"-a suffix string", won't be truncated
How to implement it in iOS ?

If you set it to NSLineBreakByTruncatingMiddleit will truncate in the middle.
You have to set the lineBreakMode. You can either do that from Interface Builder or programmatically as follows
label.lineBreakMode = NSLineBreakByTruncatingMiddle;
another Solution
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 160, 21)];
NSString *string = #"The Dark Knight Rises at 7:45pm";
NSString *substring = #"at";
CGFloat pix = 120.0;
NSString *result = [self truncatedStringFrom:string toFit:label atPixel:120.0 atPhrase:#"at"];
label.text = result;
My first idea would be two labels side-by-side both with fixed width,
but I'll assume you've ruled that out for some unstated reason.
Alternatively, compute the truncation manually, like this ...
- (NSString *)truncatedStringFrom:(NSString *)string toFit:(UILabel *)label
atPixel:(CGFloat)pixel atPhrase:(NSString *)substring {
// truncate the part of string before substring until it fits pixel
// width in label
NSArray *components = [string componentsSeparatedByString:substring];
NSString *firstComponent = [components objectAtIndex:0];
CGSize size = [firstComponent sizeWithFont:label.font];
NSString *truncatedFirstComponent = firstComponent;
while (size.width > pixel) {
firstComponent = [firstComponent substringToIndex:[firstComponent length] - 1];
truncatedFirstComponent = [firstComponent stringByAppendingString:#"..."];
size = [truncatedFirstComponent sizeWithFont:label.font];
}
NSArray *newComponents = [NSArray arrayWithObjects:truncatedFirstComponent, [components lastObject], nil];
return [newComponents componentsJoinedByString:substring];
}

Just do this and let me know..

Related

Trim last two lines of an attributed string

How do I remove the last two lines of this NSAttributedString?
NSString *exampleString = #"line 1\nline 2\nline 3\nline 4"
NSAttributedString *as = [NSAttributedString alloc] int];
[as setString:exampleString];
[self removeLastTwoLinesOfAttributedString:as];
NSLog(#"%#",as);
-(void)removeLastTwoLinesOfAttributedString:(NSAttributedString *)string {
//some code here
}
I'd like to end up with #"line 1\nline 2" in this example. Thanks
You could do something like this :
-(NSAttributedString *) removeLastTwoLinesOfAttributedString:(NSAttributedString *aString) {
NSRange range = [aString.string rangeOfString:#"\n" options:NSBackwardsSearch];
range = [aString.string rangeOfString:#"\n" options:NSBackwardsSearch range:NSMakeRange(0, range.location)];
return [aString attributedSubstringFromRange:NSMakeRange(0, range.location)];
}
int main (int argc, const char * argv[])
{
NSString *exampleString = #"line 1\nline 2\nline 3\nline 4";
NSAttributedString *as = [[NSAttributedString alloc] initWithString:exampleString];
as = [self removeLastTwoLinesOfAttributedString:as];
NSLog(#"%#",as);
return 0;
}
Output
line 1
line 2
I would suggest as the best solution:
-(NSAttributedString *)removeLastTwoLinesOfAttributedString:(NSAttributedString *)aString {
if (aString.length == 0) {
return aString
}
NSString *string = [aString string];
unsigned numberOfLines, index, stringLength = [string length];
NSRange rangeOfLastTwoLines = NSMakeRange(aString.length - 1, 0);
for (index = stringLength-1, numberOfLines = 0; index >= 0 && numberOfLines < 2; numberOfLines++) {
NSRange rangeOfLine = [string lineRangeForRange:NSMakeRange(index, 0)];
rangeOfLastTwoLines = NSUnionRange(rangeOfLastTwoLines, rangeOfLine);
index -= rangeOfLine.length;
}
return [aString attributedSubstringFromRange:NSMakeRange(0, rangeOfLastTwoLines.location)];
}
This has the benefit of working with any newline character not just "\n" and it uses the preferred by Apple method for detecting lines see this
Also it will not break if the last two lines are less than 2
If you're using Swift you can do this, if you're using Objective-C you should look at the other answers.
You can drop the last two lines of a String like this
string.components(separatedBy: "\n").dropLast(2).joined(separator: "\n")
To do it to an attributed string just access the string property, remove the last two lines, and create an attributed string with the trimmed string and all the same attributes.

Concatenation Values in IOS

How to concatenate the value from UITextField and value from button and display
them together in Objective-C? I'm trying but not getting it.
you can try this
NSString *strConcate = [NSString stringWithFormat:#"%# %#",textFeild.text,button.titleLabel.text];
NSString* aString = [NSMutableString stringWithFormat:#"String with two ints %d - %d", myInt, myInt];
NSLog(#"%#",aString);
NSString* aString = [NSMutableString stringWithFormat:#"String with two ints %d - ... now has another int: %d", myInt, myInt];
NSLog(#"%#",aString);
//suppose - int one = 1; int two = 2; int three = 3
NSString *oneTwoThree = [NSString stringWithFormat:#"%d/%d/%d", one, two, three];
NSLog(#"%#",oneTwoThree);
// suppose
//UITextField *tf = [[UITextField alloc] init];
//tf.text = "text field text"
//UIButton *btn = [[UIButton alloc] init];
//btn.titleLabel.text = "button text"
NSString* concatedString = [NSMutableString stringWithFormat:#"%# - %#", tf.text, btn.titleLabel.text];
NSLog(#"%#",concatedString); //result: "text field text = button text"

How to arrange NSString word in this type format without adding space in UILabel

I want to make this type format to word arrange in NSString on UILabel like
but I try to make add extra white space according to upper line word length but another way to make this type format suppose using NSAttributesString.
You can do this using NSMutableAttributedString without adding extra white space.
First, create a method that returns NSMutableAttributedString like this-
-(NSMutableAttributedString*)setIndent:(NSString*) title value:(CGFloat) value {
NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
style.alignment = NSTextAlignmentLeft;
style.firstLineHeadIndent = value;
NSMutableAttributedString *attrText = [[NSMutableAttributedString alloc] initWithString:title attributes:#{ NSParagraphStyleAttributeName : style}];
return attrText;
}
and use this method by the following way -
NSString *title = #"Charlie Chapline Cartoon";
NSArray* foo = [title componentsSeparatedByString: #" "];
NSMutableAttributedString *attrText5 = [[NSMutableAttributedString alloc] init];
CGFloat value = 0.0f;
for(int i = 0; i< foo.count; i++){
//change this value according to your need.
value = value + 20.0f;
[attrText5 appendAttributedString:[self setIndent:[NSString stringWithFormat:#"%#\n", foo[i]] value:value]];
}
_myLab.numberOfLines = 5;
_myLab.attributedText = attrText5;
Output:

Unicode not working properly in iOS

My unicode is \u20AC when I set it on UILabel but I'm getting unicode on label. Some time it is printing euro but mostly it is printing unicode on label.
My code is over here
NSLog(#"Currecy %#",currencySymbol);
UILabel *priceLbl = [[UILabel alloc] initWithFrame:CGRectMake(180, 10, 45, 25)];
priceLbl.textColor = [UIColor whiteColor];
priceLbl.textAlignment = NSTextAlignmentCenter;
priceLbl.font = [UIFont fontWithName:#"ProximaNova-Bold" size:15];
priceLbl.tag = 1001;
fair = [NSString stringWithFormat:#"%d",arc4random()%50];
priceLbl.text = [NSString stringWithFormat:#"%# %#",fair,currencySymbol];
Output
Currecy \u20AC
Printing description of priceLbl:
<UILabel: 0x7faade3095a0; frame = (185 10; 50 25); text = '\u20AC'; userInteractionEnabled = NO; tag = 1001; layer = <_UILabelLayer: 0x7faadbd91bb0>>
And I'm trying to set at my end getting output as I would like. for example
Getting server response
{
currency = "\\u20AC";
description = "You have been successfully logged in.";
}
and the currency symbol replacing "\\" with "\"
NSString *currency = [response[#"currency"] stringByReplacingOccurrencesOfString:#"\\\\" withString:#"\\"];
NGUYEN MINH answer worked for me as follow:
NSString *currencySymbol = #"\\u20AC";
NSString *fair = #"1.99 ";
NSString *convertedString = currencySymbol;
CFStringRef transform = CFSTR("Any-Hex/Java");
CFStringTransform((__bridge CFMutableStringRef)convertedString, NULL, transform, YES);
label.text = [NSString stringWithFormat:#"%# %#", fair, convertedString];
The problem is that your currencySymbol contains: #"\\u20AC" which is a string of 6 characters not the one character string #"\u20AC"
Another working solution:
NSString *currencySymbol = #"\\u20AC";
NSString *fair = #"1.99 ";
currencySymbol = [NSString
stringWithCString:[currencySymbol cStringUsingEncoding:NSUTF8StringEncoding]
encoding:NSNonLossyASCIIStringEncoding];
label.text = [NSString stringWithFormat:#"%# %#", fair, currencySymbol];
please try:
NSString *convertedString = #"some text"; //Your unicode string here
CFStringRef transform = CFSTR("Any-Hex/Java");
CFStringTransform((__bridge CFMutableStringRef)convertedString, NULL, transform, YES);
yourLabel.text = convertedString;
You are confusing the output of NSLog with the real data.
\u20ac is how NSLog displays a Euro symbol, because the Euro symbol is the Unicode character u20ac.

lineBreakMode for multiline attributed string

I have a multiline label that will contain an attributed string. This is the code of the attributed string:
NSString * titleString = #"Title";
NSString * informationString = self.myObject.content;
NSString * allString = [NSString stringWithFormat:#"%#\n\n%#",titleString,informationString];
NSMutableAttributedString* attributedMessage = [[NSMutableAttributedString alloc]initWithString:allString];
NSMutableParagraphStyle* style=[[NSMutableParagraphStyle alloc]init];
style.alignment = NSTextAlignmentLeft;
NSDictionary *attributesTitle = [NSDictionary dictionaryWithObjectsAndKeys:style,NSParagraphStyleAttributeName,[UIColor blackColor],NSForegroundColorAttributeName,[UIColor clearColor],NSBackgroundColorAttributeName,Font(#"OpenSans-Semibold", 17+(int)((self.view.bounds.size.width-290.)/15.)),NSFontAttributeName,nil];
NSMutableParagraphStyle* styleText=[[NSMutableParagraphStyle alloc]init];
styleText.alignment = NSTextAlignmentLeft;
styleText.lineBreakMode = NSLineBreakByTruncatingTail;
NSDictionary *attributesInformation = [NSDictionary dictionaryWithObjectsAndKeys:styleText,NSParagraphStyleAttributeName,[UIColor colorWithRed:91./255 green:91./255 blue:91./255 alpha:1.],NSForegroundColorAttributeName,[UIColor clearColor],NSBackgroundColorAttributeName,[UIFont fontWithName:#"Roboto-Light" size:13.+(int)((self.view.bounds.size.width-290.)/15.)],NSFontAttributeName,nil];
[attributedMessage setAttributes:attributesTitle range:[allString rangeOfString:titleString]];
[attributedMessage setAttributes:attributesInformation range:[allString rangeOfString:informationString]];
In my case the label is shown with ellipse "..." in all the lines. how can i resolve this issue. I want that will be shown only in the last visible line.
The solution that i adopted is
while (newHeight>=heightOfLabel){
remove some letter from the end of the string
calculate new height
}
replace the last three charachter with "..."
and it is done :)
I know that it is not a clean solution but it resolve my issue until finding a clean one.

Resources