Access last line while using UILineBreakModeWordWrap UILabel in iPhone - iphone

I am displaying a long string using UILabel with UILineBreakModeWordWrap. It is showing the string perfectly by wrapping text in UILabel. I want to access last line of UILabel. Does anyone know how to do this on an iPhone?

So I tried some stuff and searched a little around. What you wuld actually need is to count the word wraps and somehow detect the last string. But I didnt really figuere out how to do that.
So my sollution is something like this:
Your String //I googled some longer String
NSString *string = #"Standing across the room, I saw you smile\nSaid I want to talk to you-oo-oo for a little while\nBut before I make my move my emotions start running wild\nMy tongue gets tied and that's no lie\nLooking in your eyes\nLooking in you big brown eyes ooh yeah\nAnd I've got this to say to you\nHey!\nGirl I want to make you sweat\nSweat till you can't sweat no more\nAnd if you cry out\nI'm gonna push it some, more, more\nGirl I want to make you sweat\nSweat till you can't sweat no more\nAnd if you cry out\nI'm gonna push it\nPush it, push it some more";
Your Label:
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, 280, 440)];
label.font = [UIFont fontWithName:#"Helvetica" size:14];
label.lineBreakMode = UILineBreakModeWordWrap;
label.numberOfLines = 0;
label.backgroundColor = [UIColor clearColor];
label.textColor = [UIColor blackColor];
label.text = string;
The call this Method:
NSString *result = [self getLastLineFromString:string];
NSLog(#"Result: %#", result);
getLastLineFromString: looks like this:
- (NSString *)getLastLineFromString: (NSString *)string{
NSArray *a = [string componentsSeparatedByString:#" "];
NSString *result = [a objectAtIndex:[a count]-1];
NSString *temp = #"";
int count = 1;
BOOL myBool = YES;
while (myBool) {
count++;
temp = result;
result = [a objectAtIndex:[a count] -count];
result = [NSString stringWithFormat:#"%# %#", result, temp];
NSLog(#"length: %i",[self lengthOfString:result]);
NSLog(#"result: %#",result);
//131 was a value i detected mayels, i guess u have do trick a little around to find a mathcing one for yourself
if ([self lengthOfString:result] >= 131) {
myBool = NO;
}
}
return result;
}
And The MethodlengthOfString: looks like this:
- (int)lengthOfString:(NSString *)string{
CGSize size1 = [string sizeWithFont:[UIFont fontWithName:#"Helvetica" size:14]];
return size1.width;
}
Output:
2012-01-06 16:17:08.341 get length[5472:207] result: it
Push it, push it some more
I know this is not a perfect sollution, but it might help you.

Related

limit the UILabel to 500 character and than Truncate the UIlabel in IOS

I want to display first 500 character in UILabel and than display Truncate icon if there is more than 500 character available.But i dont know how can i limit 500 character to truncate the text?.
Here is my code
label2 = [[UILabel alloc] initWithFrame:CGRectMake(0, 350, self.bounds.size.width, 30)];
// In this case value of self.bounds.size.width is "427"
label2.backgroundColor = [UIColor clearColor];
label2.numberOfLines = 2;
label2.textAlignment = UITextAlignmentCenter;
label2.font = [UIFont systemFontOfSize:13];
[self addSubview:label2]
//Here is Implimentation code of my label
NSString *temp = [galleryEntryTree objectForKey:#"description"];// calling lebel text from database
coverView.label2.text = temp;
coverView.label2.adjustsFontSizeToFitWidth = NO;
coverView.label2.lineBreakMode = UILineBreakModeTailTruncation;
Just tell me guys how can i display min 500 character and than truncate it( if longer than 500)
Any help is appreciated
Just truncate the string if it's longer than 500 characters. Only caveat: make sure to not break it in the middle of a surrogate pair:
NSString *temp = [galleryEntryTree objectForKey:#"description"];
if ([temp length] > 500) {
NSRange range = [temp rangeOfComposedCharacterSequencesForRange:(NSRange){0, 500}];
temp = [temp substringWithRange:range];
temp = [temp stringByAppendingString:#" …"];
}
coverView.label2.text = temp;
To display only 500 character just use below code:
NSString *string = YOUR_TEXT;
if ([string length] >500) {
string = [string substringToIndex:500];
}
Hope this will help you.
All the best !!!
Here is how to do it in Swift 2.2:
let maxLength = 500
if originalString.characters.count > maxLength {
let range = originalString.rangeOfComposedCharacterSequencesForRange(Range<String.Index>(originalString.startIndex ..< originalString.startIndex.advancedBy(maxLength)))
let tmpValue = originalString.substringWithRange(range).stringByAppendingString(" …")
// use tmpValue
}
try this one it'l helps you.
label2 = [[UILabel alloc] initWithFrame:CGRectMake(0, 350, self.bounds.size.width, 30)];
// In this case value of self.bounds.size.width is "427"
label2.text=#"your text................................";
if([label2.text length]>500)
label2.text=[label2.text substringToIndex:500];
label2.backgroundColor = [UIColor clearColor];
label2.numberOfLines = 2;
label2.textAlignment = UITextAlignmentCenter;
label2.font = [UIFont systemFontOfSize:13];
[self addSubview:label2]
It can be simply done by
NSString *LabelNewText = [YourLabelName.text substringToIndex:500];
Here 500 or less than 500 characters will be displayed and all the characters exceeding that will be truncated.
NSString *string = LabelNewText.text;
if ([string length] >500)
{
string = [string substringToIndex:500];
}
Swift 3.0 version
let maxLength = 300 //char length
if originalString.characters.count > maxLength {
let range = originalString.rangeOfComposedCharacterSequences(for: originalString.startIndex..<originalString.index(originalString.startIndex, offsetBy: maxLength))
let tmpValue = originalString.substring(with: range).appending("...")
}

Xcode write NSLog result in UILabel

I use NSLog(#"%#");
And the NSLog result is '23204239423'
I don't explain you why ... it's just an example.
I want the NSLog result appear in UILabel, is it possible ?
I tried : Label.text = (#"%#"); , it doesn't work.
Do you know how i can do it ?
Thanks.
NSLog usually takes a string like:
NSLog(#"%#", string);
So instead just do this:
label.text = [NSString stringWithFormat:#"%#", string];
You have to put a variable
NSString *text = #"My Text";
label.text = text;
Or
label.text = #"Your text";

Appending a string with string in ios

I am in a problem with some text sharing to evernote,sharing evernote is success,but here is my current situation with code. I have a UITableView which has some text and title for that corresponding text. When the share button is clicked it will share the text onebyone to evernote website, but the title remains static. There I get the first title name along with diffrent text. My code for this is in my tableview in rowAtIndexPath
NSMutableString *strr=[[NSMutableString alloc]initWithString:[appDelegate.indexArray objectAtIndex:indexPath.section]];
cell.textLabel.text =strr ;
cell.textLabel.text = [appDelegate.indexArray objectAtIndex:row];
cell.textLabel.font = [UIFont fontWithName:#"Georgia" size:14.0];
cell.textLabel.textColor = [UIColor brownColor];
[appDelegate.notesArray objectAtIndex:row]];
//cell.detailTextLabel.text =notes;
cell.detailTextLabel.font = [UIFont fontWithName:#"Georgia" size:14.0];
cell.detailTextLabel.textColor = [UIColor darkGrayColor];
cell.detailTextLabel.text = [appDelegate.notesArray objectAtIndex:row];
appDelegate.indexArray is the title content for each cell and appDelegate.notesArray has the textnote for the corresponding titles.
In shareButton click:
NSMutableString *str = [[NSMutableString alloc] initWithString:#"NOTES:"];
for (int i = 0; i<[appDelegate.notesArray count]; i++) {
NSString * aString = [[NSString alloc] initWithString:[appDelegate.notesArray objectAtIndex:i]] ;
NSString * ENML= [NSString stringWithFormat:#"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">\n<en-note>%#",aString];
ENML = [NSString stringWithFormat:#"%#%#", ENML, #"</en-note>"];
NSLog(#"%#", ENML);
// Adding the content & resources to the note
[note setContent:ENML];
This will give the one by one upload of notetext.but for title I include this code
NSMutableString *strtitle = [[NSMutableString alloc] initWithString:#"myBibleApp"];
for (int i = 0; i<[appDelegate.indexArray count];i++ ) {
NSString * aStringtitle = [[NSString alloc] initWithString:[appDelegate.indexArray objectAtIndex:i]] ;
/* NSString *ENMLtitle = [NSString stringWithFormat:#"%#%#", aStringtitle];
NSLog(#"%#", ENMLtitle);*/
note.title = aStringtitle;
But here is my problem it uplode the title and text in double. That means, I have one text with title. When I click the sharebutton it uploads two times.1=2,2=4,3=6 like that.
Nut only addding the title I get this problem. If I put the title static,note.title =#"statictitle". It will not repeat the upload. How can I append the string in correct way?
Please help me.
Thanks in advance.
Two things I noted:
The use of NSMutableString is not needed. Just write for the first case
cell.textLabel.text = [appDelegate.indexArray objectAtIndex:indexPath.section];
For the 2 other cases you don't use the string at all (or it's not shown in your code).
In the for-loops, you're always overwriting aString and aStringtitle, and that even with a new alloc. Appending goes like this:
NSString *aString = #"";
for ...
aString = [aString stringByAppendingString:[appDelegate.indexArray objectAtIndex:i]];
or
aString = [aString stringByAppendingFormat:#" %#", [appDelegate.indexArray objectAtIndex:i]];
Check the NSString Class Reference for details.

Accurately and seamlessly splitting text into two UILabels

I'm trying to create a "wrapping" like effect for text around an image that has set dimensions.
___________
........|
........| image
label.1.|
........|___________
....................
.......label.2......
....................
....................
Here is the method im using right now:
- (NSArray *)splitString:(NSString*)str maxCharacters:(NSInteger)maxLength { //this will split the string to add to two UILabels
NSMutableArray *tempArray = [NSMutableArray arrayWithCapacity:1];
NSArray *wordArray = [str componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSInteger numberOfWords = [wordArray count];
NSInteger index = 0;
NSInteger lengthOfNextWord = 0;
while (index < numberOfWords) {
NSMutableString *line = [NSMutableString stringWithCapacity:1];
while ((([line length] + lengthOfNextWord + 1) <= maxLength) && (index < numberOfWords)) {
lengthOfNextWord = [[wordArray objectAtIndex:index] length];
[line appendString:[wordArray objectAtIndex:index]];
index++;
if (index < numberOfWords) {
[line appendString:#" "];
}
}
[tempArray addObject:line];
}
return tempArray;
}
I give it the maxCharacters value of where I want to split the text, which is the max height of the first UILabel. This method is essentially what I want, but sometimes the last line of the first UILabel is "higher" than others leaving a gap between the first UILabel and the second UILabel.
Here is how I use the method:
NSArray *splitStringArray = [self splitString:eventRecord.summary maxCharacters:280];
UILabel *firstSumValue = [[UILabel alloc] init];
NSString *firstSumString = [splitStringArray objectAtIndex:0];
CGSize maxFirstSumSize = CGSizeMake(185.0,150.0);
UIFont *firstSumFont = [UIFont fontWithName:#"HelveticaNeue-Bold" size:12];
CGSize firstSumStringSize = [firstSumString sizeWithFont:firstSumFont
constrainedToSize:maxFirstSumSize
lineBreakMode:firstSumValue.lineBreakMode];
CGRect firstSumFrame = CGRectMake(10.0, presentedValue.frame.origin.y + presentedValue.frame.size.height, 185.0, firstSumStringSize.height);
firstSumValue.frame = firstSumFrame;
firstSumValue.font = [UIFont fontWithName:#"HelveticaNeue" size:12];
firstSumValue.lineBreakMode = UILineBreakModeWordWrap;
firstSumValue.numberOfLines = 0 ;
[self.mainScrollView addSubview:firstSumValue];
firstSumValue.text = [splitStringArray objectAtIndex:0];
UILabel *secondSumValue = [[UILabel alloc] init];
NSInteger isSecond = 0; //no
if([splitStringArray count] > 1){
isSecond = 1; //yes
NSString *secondSumString = [splitStringArray objectAtIndex:1];
CGSize maxSecondSumSize = CGSizeMake(310.0,9999.0);
UIFont *secondSumFont = [UIFont fontWithName:#"HelveticaNeue-Bold" size:12];
CGSize secondSumStringSize = [secondSumString sizeWithFont:secondSumFont
constrainedToSize:maxSecondSumSize
lineBreakMode:secondSumValue.lineBreakMode];
CGRect secondSumFrame = CGRectMake(10.0, firstSumValue.frame.origin.y + firstSumValue.frame.size.height, 310.0, secondSumStringSize.height);
secondSumValue.frame = secondSumFrame;
secondSumValue.font = [UIFont fontWithName:#"HelveticaNeue" size:12];
secondSumValue.lineBreakMode = UILineBreakModeWordWrap;
secondSumValue.numberOfLines = 0 ;
[self.mainScrollView addSubview:secondSumValue];
secondSumValue.text = [splitStringArray objectAtIndex:1];
}
How do I keep everything consistent and aligned properly. Perhaps, there is a better method one could recommend. Not core text because it's out of my scope of knowledge.
Consider using a UIWebView instead, with the layout defined in a local HTML file. It can save you a lot of headache rather than trying to deal with complex layouts by hand.

TTT attributed Label Multi- colored Font help

-(UITableViewCell*) makeLikeCell
{
// Load the top-level objects from the custom cell XIB.
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"SpotlightLikesTableViewCell" owner: self options: nil];
// Grab a pointer to the first object (presumably the custom cell, as that's all the XIB should contain).
UITableViewCell *cell = [topLevelObjects objectAtIndex:0];
NSString *likeText = [likesAndComments objectAtIndex: kLikeRow];
TTTAttributedLabel *likeLabel = [[[TTTAttributedLabel alloc] initWithFrame:CGRectZero] autorelease];
likeLabel = (TTTAttributedLabel*) [cell viewWithTag: kCaptionTag];
likeLabel.textColor = [UIColor blueColor];
likeLabel.lineBreakMode = UILineBreakModeWordWrap;
[likeLabel setFont: [UIFont fontWithName: #"Helvetica Neue" size: 10]];
[likeLabel setText: likeText afterInheritingLabelAttributesAndConfiguringWithBlock: ^NSAttributedString *(NSMutableAttributedString *mutableAttributedString) {
NSRange colorRange = [[mutableAttributedString string] rangeOfString: #" like this photo." options: NSCaseInsensitiveSearch];
[mutableAttributedString addAttribute:(NSString *) kCTForegroundColorAttributeName value:(id)[[UIColor grayColor] CGColor] range:colorRange];
return mutableAttributedString; }];
return cell;
}
I added the TTT attributed label to my project. I want to have 2 different font colors to display the "likes". However my project keeps crashing. A sample string to be formatted would be: "andrew, john, amos likes this photo."
any suggestions?
Use like this
[likeLabel setText:likeText afterInheritingLabelAttributesAndConfiguringWithBlock: ^(NSMutableAttributedString *mutableAttributedString) {
NSRange colorRange = [likeText rangeOfString: #"like this photo." options: NSCaseInsensitiveSearch];
if (colorRange.location != NSNotFound) {
[mutableAttributedString addAttribute:(NSString *) kCTForegroundColorAttributeName value:(id)[[UIColor grayColor] CGColor] range:colorRange];
}
return mutableAttributedString;
}];
There is a way to set different / multiple fonts & other properties like color on Label using NSMutableAttributedStrin. Refer to my answer on Multiple Font & Color for string & Display the string on Label