I'm still sort of new to Xcode, so please be patient with me. Anyway, I'm having a bit of trouble trying to display the whole contents of an array in a UILabel. I'm able to display it by simply using the code
wordList.text = [NSString stringWithFormat:#"List of Words:\n %#", listA];
However upon running, the label ends up displaying a parenthesis and the words on their own lines, as well as quotation marks around the words, and the ending quotation mark and a comma in the line between each word. Example:
List of Words:
(
"apple
",
"banana
",
"etc.
While I do want the words to be displayed in their own lines, I do not want the parenthesis and the closing quotation mark and comma being displayed in a separate line. I would also prefer removing the parenthesis, quotation marks, and commas all together, but I wouldn't mind too much if I'm unable to.
Could anyone please explain why its being displayed as such, and to help me correctly display each word of an array in its own line in a UILabel?
Use this:
NSArray *listOfWords = #[#"One", #"Two", #"Three"];
NSString * stringToDisplay = [listOfWords componentsJoinedByString:#"\n"];
wordList.text = stringToDisplay;
Will Display:
One
Two
Three
The parentheses, quotation marks, and commas are being added because providing an array as an argument to the format specifier %# causes the -(NSString *)description method to be sent to the array. NSArray overrides NSObject's implementation of description and returns a string that represents the contents of the array, formatted as a property list. (As opposed to just returning a string with the array's memory address.) Hence, the extra characters.
You Can use this Code
NSArray *listOfWords = [NSArray arrayWithObjects:
#"one.",
#"two.",
nil];
for (NSString *stringToDisplay in matters)
{
//frame, setting
labelFrame.origin.x = 20.0f;
UILabel *stringToDisplayLabel = [[UILabel alloc] initWithFrame:labelFrame];
stringToDisplayLabel.backgroundColor = [UIColor clearColor];
stringToDisplayLabel.font = [UIFont boldSystemFontOfSize:12.0f];
stringToDisplayLabel.lineBreakMode = NSLineBreakByWordWrapping;
stringToDisplayLabel.numberOfLines = 0;
stringToDisplayLabel.textColor = [UIColor whiteColor];
stringToDisplayLabel.textAlignment = NSTextAlignmentLeft;
//set up text
stringToDisplayLabel.text = stringToDisplay;
//edit frame
[stringToDisplayLabel sizeToFit];
labelFrame.origin.y += stringToDisplayLabel.frame.size.height + 10.0f;
[self.view addSubview:stringToDisplayLabel];
[matterLabel release];
}
Related
I have a UILabel which usually has to display one or two words.
Many times one of the words doesn't fit into one line, so I would like to reduce font size in order to fit each word at least in one line (not breaking by character).
Using the technique described in http://beckyhansmeyer.com/2015/04/09/autoshrinking-text-in-a-multiline-uilabel/
self.numberOfLines = 2;
self.lineBreakMode = NSLineBreakByTruncatingTail;
self.adjustsFontSizeToFitWidth = YES;
self.minimumScaleFactor = 0.65;
I've found that it plays well when the second word doesn't fit in just one line.
But it doesn't when there is just one word, or the first word is the one
that doesn't fit.
I managed to solve the case of just one word doing this:
-(void)setText:(NSString *)text
{
self.numberOfLines = [text componentsSeparatedByString:#" "].count > 1 ? 2 : 1;
[super setText:text];
}
But how could I solve those cases where the first word doesn't fit?? Any ideas?
How about this ?
self.numberOfLines = [text componentsSeparatedByString:#" "].count;
[self setAdjustsFontSizeToFitWidth:YES];
But, this will rule out the case where your label text consists of two very small words, eg."how are". In such cases, the entire string will be visible in the first line itself. If it is your requirement to display each word in a separate line then i would recommend you adding a '\n' after every word. This means that you will have to edit the string before assigning it to the label. Thus, a universal solution could be like :
NSString *string = #"how are"; //Let this be the string
NSString *modifiedString = [string stringByReplacingOccurrencesOfString:#" " withString:#"\n"];
[self setText:modifiedString];
[self setTextAlignment:NSTextAlignmentCenter];
[self setAdjustsFontSizeToFitWidth:YES];
[self setNumberOfLines:0];
self.lineBreakMode = NSLineBreakByWordWrapping;
I am interested in finding the localized string key for a given text on the screen.
Is this possible ?
For instance in a contrived example:
UILabel *label = [[UILabel alloc] initWithFrame:frame];
label.text = NSLocalizedString(#"The key for this label",nil);
// at runtime
UILabel *theLabel = ... // get the label
NSString *text = theLabel.text;
NSLog(#"%#",text); // prints "Foo bar"
// now I want to get the key:
NSString *localizedKey = ???? NSLocalizedStringReverseLookup(text)
NSLog(#"%#",localizedKey); // should print "The key for this label"
You can do this in some cases as nburk said, but you cannot do it in others:
It is possible that different keys refers to the same string. You cannot find out, which key was the original one.
Strings on screens can contain data pasted into the string via %…. You will not find the string then.
Why do you want to do this?
is there a way to limit number of lines in paragraph in NSAttributedString?
Im appending two strings in NSAttributedString and i want them to be maximum 3 lines, the first string will be 1-2 lines , truncated if needed. and the second string should be always on the last line
Something like:
this is my first string
if its too long i't will get trun...
But this is my second string
what i did is:
// First string
NSAttributedString *first = [[NSAttributedString alloc] initWithString:#"this is my first string if its too long i't will get trunticated"
attributes:#{NSForegroundColorAttributeName:[UIColor redColor],
NSFontAttributeName:[UIFont fontWithName:#"HelveticaNeue-Light" size:17.0]];
[str appendAttributedString:first];
// New line
[str appendAttributedString:[[NSAttributedString alloc] initWithString:#"\n"]];
// Add photo count
NSAttributedString *second = [[NSAttributedString alloc] initWithString:#"But this is my second string"
attributes:#{NSForegroundColorAttributeName:[UIColor redColor],
NSFontAttributeName:[UIFont fontWithName:#"HelveticaNeue-Light" size:14.0]}];
[str appendAttributedString:second];
But the result is:
this is my first string
if its too long i't will get
trunticated
The first string takes the first 3 lines and push the second string out of the label.
How can i limit the first string paragraph to 2 lines?
You can count the amount of letters that your graphic component (UITextView or UITextField) can handle using uppercase and bigger width ones repeatedly to see this. Than, use:
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{}
to check every input, if the amount is enough, or if it stills available for more letters. Create a character limit and decrease it everytime this method is called.
Limit the number of lines with one constraint !
Simply add a NSLayoutConstraint on your UILabel with following values :
attribute = NSLayoutAttributeHeight ('Height' in Storyboard)
relation = NSLayoutRelationLessThanOrEqual ('Less Than or Equal' in Storyboard)
constant = height-for-number-of-lines-you-want
See Storyboard integration :
My requirement is that I need to display text in label in such a way that if the length of text is too big to accommodate in one line, i need to truncate it at the end in such a way that only the last few characters(usually a number b/w 1-1000 so text length may vary.) are visible and the text before it is truncated with "...".
So the text will look something like "abcdefgijk...10"
Is there any way I can achieve this?
UILabel *contentLabel = [[UILabel alloc]initWithFrame:CGRectMake(50,100, 150, 30)];
contentLabel.text = #"abcdefghijklmnopqrstuvwxyz10";
contentLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
Add this label to your display. You should get a output something like this
abcdefghijklmnopq...10
Swift 4:
Incase someone runs into this issue like i did,
you need to set your label.numberOfLines = 1
if you have it set to 0 it will truncate at a space.
so your code should look like
label.numberOfLines = 1
label.lineBreakMode = .byTruncatingTail
label.adjustsFontSizeToFitWidth = false
For everyone looking for more recent solution, swift 3 :
yourLabel.lineBreakMode = .byTruncatingMiddle;
Try this:
label.lineBreakMode = NSLineBreakByTruncatingMiddle;
UILineBreakModeMiddleTruncation is deprecated from iOS 6.0.
In Storyboard
Select the Label which you want to truncate the characters.
Choose Attributes Inspector.
Under Label attributes. You can find Line Break
Done.
there are many methods in NSString class use -length and then use any of these
– substringFromIndex:
– substringWithRange:
– substringToIndex:
create a temporary string using NSString stringwithFormat, put your desired charecters you get from substringTo index and "....." then your numbers from string by substringFromIndex.
hope this helps
You can start with finding the length of characters that can be placed in a line, say 'n' characters. You can take help of this link to determine 'n' How to know if NSString fits in UILabel or not and index of the last string which fits?. Next, find the length of the string. If it exceeds n, then extract the last two characters. Ex
NSString * fooString = #"a very long string";
NSString * s2 = [fooString substringWithRange:NSMakeRange([fooString length]-3, 2)];
NSString * s1 = [fooString substringWithRange:NSMakeRange(0 , n-5)];
NSString * newString = [NSString stringWithFormat:#"%#...%#",s1,s2];
We have different Line Break modes for UILabel like
Truncate Head,
Truncate Middle,
Truncate Tail
In Xib you can set the Line Break mode what ever you want
If you using XIB file..
select --> UILable and
select --> Attribute inspector tag and change into Line Breaks-->Truncate tail
simply way to truncate characters...
Here is how to use it, NSLineBreakByTruncatingMiddle
UILabel *temp = [[UILabel alloc]initWithFrame:CGRectMake(5,75, 100, 50)];
[temp setBackgroundColor:[UIColor lightGrayColor]];
temp.lineBreakMode = NSLineBreakByTruncatingMiddle;
temp.text = #"HelloBoss997";
Output :
Hello...s997
Tricky to write the subject to this. I guess this is a basic question but I can't seem to find the answer.
The code itself shows what I wanna do and the UILabel don't show anything, the first line I add to it works fine, but not when I try to write out the array:
-(IBAction)getSongHistory:(id)sender {
[historyLabel setText:#"test write\n test write another line"];
NSArray *pastMusicArray = [pastSongs getHistory];
for(int t=2; t<[pastMusicArray count]; t++) {
NSString *tempRow = [pastMusicArray objectAtIndex:t];
//NSLog(#"%#", tempRow);
[historyLabel setText:tempRow];
[historyLabel setText:#"\n"];
}
}
The NSLog do put out the right stuff.
What is gong on here, that I am not seeing?
Seems to me that the problem is that you are setting the full text each time and the last setText: is with #"\n" which is an invisible string. Try appending instead of setting the text. Something like:
historyLabel.text = [NSString stringWithFormat:#"%#%#", historyLabel.text,#"TextToAppend"];
This will append #"TextToAppend" to the current text value in the label.
Update: Notice I'm using the text property rather than the setter.
historyLabel.text = #"Some Text";
is equivalent to
[historyLabel setText:#"Some Text"];
Using \n in a string should be fine, try to set numberOfLines property of the label to 0, which allow any number of lines in it.
This is the solution for my own problem. Hope that it can help someone else.
NSArray *pastMusicArray = [pastSongs getHistory];
musicHistory = [[NSMutableString alloc] init];
historyLabel.numberOfLines = 0;
for(int t=2; t<[pastMusicArray count]; t++) {
[musicHistory appendString:[[pastMusicArray objectAtIndex:t] capitalizedString]];
[musicHistory appendString:#"\n"];
}
historyLabel.text = musicHistory;