Appending a string with string in ios - iphone

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.

Related

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.

Access last line while using UILineBreakModeWordWrap UILabel in 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.

How to display x raise to y in UIlabel

how can I display 5 raise to 1/3 in iphone i.e I want 1/3 written above 5 can anyone help please
I Found this solution, hope so it would be helpful for you.
x to the power of y in a UILabel could be easy. Just replace your indices with unicode superscript characters... I use the following method to turn an integer into a string with superscript characters.
+(NSString *)convertIntToSuperscript:(int)i
{
NSArray *array = [[NSArray alloc] initWithObjects:#"⁰", #"¹", #"²", #"³", #"⁴", #"⁵", #"⁶", #"⁷", #"⁸", #"⁹", nil];
if (i >= 0 && i <= 9) {
NSString *myString = [NSString stringWithFormat:#"%#", [array objectAtIndex:i]];
[array release];
return myString;
}
else {
NSString *base = [NSString stringWithFormat:#"%i", i];
NSMutableString *newString = [[NSMutableString alloc] init];
for (int b = 0; b<[base length]; b++) {
int temp = [[base substringWithRange:NSMakeRange(b, 1)] intValue];
[newString appendString:[array objectAtIndex:temp]];
}
[array release];
NSString *returnString = [NSString stringWithString:newString];
[newString release];
return returnString;
}
}
Try this NSString *cmsquare=#"cm\u00B2";
It will display cm².
Yes you can do that but you need custom UILabel, either Make it by yourself or Get it Open Source..

Objects added as subview to scrollview are not showing up

I am trying to add elements to a scroll view using this code:
int missionCount;
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSDictionary *missionsDict = [responseString JSONValue];
/*NSArray *luckyNumbers = [json objectWithString:responseString error:&error];*/
NSLog(#"user Info array is: %#", missionsDict);
// NSDictionary *array = [luckyNumbers1 objectForKey:#"data"];
NSDictionary *missionsData;
missionsData = [missionsDict objectForKey:#"data"];
NSLog(#"missionsData is: %#", missionsData);
NSEnumerator *inner = [missionsData objectEnumerator];
missionsScroll.contentSize = CGSizeMake(768, 1005);
id value;
int badgeY1;
int badgeY2;
int badgeY3;
badgeY1 = 146;
badgeY2 = 188;
badgeY3 = 188;
while((value = [inner nextObject])) {
NSLog(#"value is: %#", value);
NSLog(#"progress is: %#", [value objectForKey:#"progress"]);
NSLog(#"user Info array is: %#", missionsDict);
NSLog(#"name is: %#",[value objectForKey:#"reward_definitions"]);
NSLog(#"missionsData is: %#", missionsData);
NSDictionary *moreData;
moreData = [value objectForKey:#"reward_definitions"];
NSEnumerator *inner2 = [moreData objectEnumerator];
id value2;
int badgeX;
int badgeCount;
badgeX = 0;
badgeCount = 0;
while((value2 = [inner2 nextObject])) {
UIProgressView *progressView;
progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(323, badgeY1, 372, 9)];
float progressValue;
progressValue = ([[[value objectForKey:#"progress"] objectForKey:#"earned"] floatValue] / [[[value objectForKey:#"progress"] objectForKey:#"possible"] floatValue]);
NSLog(#"progressValue is: %f", progressValue);
[progressView setProgress:progressValue];
[missionsScroll addSubview:progressView];
UILabel *missionName;
missionName = [[UILabel alloc] initWithFrame:CGRectMake(66, badgeY1, 227, 21)];
missionName.backgroundColor = [UIColor clearColor];
missionName.textColor = [UIColor whiteColor];
missionName.font = [UIFont fontWithName:#"Heiti TC" size:23.0];
missionName.text = [value objectForKey:#"name"];
[missionsScroll addSubview:missionName];
UILabel *requirementsLabel;
requirementsLabel = [[UILabel alloc] initWithFrame:CGRectMake(66, badgeY2+25, 227, 21)];
requirementsLabel.backgroundColor = [UIColor clearColor];
requirementsLabel.textColor = [UIColor whiteColor];
requirementsLabel.font = [UIFont fontWithName:#"Papyrus" size:19];
requirementsLabel.text = #"To complete you need:";
[missionsScroll addSubview:requirementsLabel];
NSLog(#"Image URL is: %#", [value2 objectForKey:#"image_url"]);
NSURL *url1 = [NSURL URLWithString: [NSString stringWithFormat:#"%#", [value2 objectForKey:#"image_url"]]];
NSData *urlData1 = [NSData dataWithContentsOfURL:url1];
UIImage *image1 = [UIImage imageWithData:urlData1];
UIImageView *badge = [[UIImageView alloc] initWithImage:image1];
[badge setFrame:CGRectMake(badgeX, badgeY2+70, 70, 70)];
[missionsScroll addSubview:badge];
[badge release];
badgeCount = badgeCount+1;
NSLog(#"badgeCount is: %i", badgeCount);
if (badgeCount == 4) {
NSLog(#"Badge Count = 4");
badgeY2 = badgeY2 +70;
badgeX = 0;
badgeCount = 0;
} else {
NSLog(#"Badge Count ≠ 4");
badgeX = badgeX +75;
}
}
NSLog(#"1st While loop done");
// NSLog(#"reward_definitions is: %#", [missionsData objectForKey:#"id"]);
// NSLog(#"Image URL is: %#", [[value objectForKey:#"reward_definitions"] objectForKey:#"image_url"]);
//if ( [array isKindOfClass:[NSDictionary class]] ) {
badgeY1 = badgeY1 +200;
badgeY2 = badgeY2 +200;
badgeY3 = badgeY3 +200;
missionCount = missionCount+1;
}
NSLog(#"While loops done");
for (int a; missionCount > 4; a = a+1) {
missionsScroll.contentSize = CGSizeMake(776, missionsScroll.contentSize.height+200);
}
Nothing is showing up in the scroll view.
It's not obvious what is happening, but first things to check are where the views are valid (not nil) and that this code is running on the main thread.
Put these in and post the results.
NSLog(#"missionsScroll: %#", (missionsScroll==nil)?#"NIL":#"OK");
NSLog(#"progressView: %#", (progressView==nil)?#"NIL":#"OK");
NSLog(#"missionName: %#", (missionName==nil)?#"NIL":#"OK");
NSLog(#"mainThread: %#", ([NSThread isMainThread])?#"OK":#"Background Thread");
Your code is quite convoluted and very difficult to read. Perhaps you could check if your complicated coordinates calculations work as expected, e.g.
NSLog(#"Frame of badge %#", NSStringFromCGRect(badge.frame));
How many times are your while loops iterating? The outer loop increases the y-position of your labels. But the labels will only be displayed at the end of the run loop / start of the next run loop. If you exit this method with the labels with a high y-value then you'll not see them. (It doesn't matter how many times you change the y-value while you're running this code. The display will only update when it's all done.)
** Correction ** You seem to be adding new views each time around your while loop. So in fact I'd expect you to have multiple copies of the subviews appearing when they finally get displayed.
(There's a lot of code to wade through here. If my answer is way off, you might get better answers, but trimming back some of the code and isolating the issue.)

Capture first line of NSString

How do I capture the first line from a NSString object?
I currently am assigning the entire NSString object to the title of my textView, but only want to assign the first line of the string. My current code like this this:
self.textView.text = [[managedObject valueForKey:#"taskText"] description];
You want
self.textView.text = [[[[managedObject valueForKey: #"taskText"] description] componentsSeparatedByString: #"\n"] objectAtIndex:0];
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html
If you’re targeting iOS 4.0 and later, you can use -[NSString enumerateLinesUsingBlock:]:
__block NSString *firstLine = nil;
NSString *wholeText = [[managedObject valueForKey:#"taskText"] description];
[wholeText enumerateLinesUsingBlock:^(NSString *line, BOOL *stop) {
firstLine = [[line retain] autorelease];
*stop = YES;
}];
self.textView.text = firstLine;
An alternative approach which is probably the most efficient and straightforward:
NSString* str = [[managedObject valueForKey:#"taskText"] description];
self.textView.text = [str substringWithRange:[str lineRangeForRange:NSMakeRange(0, 0)]];