-(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
Related
I have to implement bubble messages with the senders AVATAR and Sender's name with time-stamps same as below screen shot.
I have successfully implemented the simple bubble type messaging. Right now I have some good Git-hub projects which provide me but what I need is something different.
I had even used acanichat but no luck.
so can anyone suggest me good tutorial for the same? or anyone have already done this with this Git-hub Library or with any other library?
I want a bubble-message with the senders AVATAR and Sender's name with time-stamps, please take a look at following image.
Your suggestion are appreciable.
Why not you create your own chat Table ? You just need to create Two custom Cells and With the help of XIB file you can give any Look you want.
Use Differentiators and conditions like Below.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier1 = #"Cell1";
static NSString *CellIdentifier2 = #"Cell2";
CGSize boundingSize = CGSizeMake(messageWidth-20, 10000000);
CGSize itemTextSize = [messageText sizeWithFont:[UIFont systemFontOfSize:14]
constrainedToSize:boundingSize
lineBreakMode:NSLineBreakByWordWrapping];
float textHeight = itemTextSize.height+7;
if (messageType isEqualToString:#"textByme"]) {
CustomCell1 *cell = (CustomCell1 *)[self.tableview dequeueReusableCellWithIdentifier:CellIdentifier1];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"CustomCell1" owner:self options:nil];
cell = [topLevelObjects objectAtIndex:0];
}
UIImageView *bubbleImage=[[UIImageView alloc] initWithImage:[[UIImage imageNamed:#"chatbubble"] stretchableImageWithLeftCapWidth:15 topCapHeight:15]];
bubbleImage.tag=55;
[cell.contentView addSubview:bubbleImage];
[bubbleImage setFrame:CGRectMake(255-itemTextSize.width,5,itemTextSize.width+10,textHeight)];
UITextView *messageTextview=[[UITextView alloc]initWithFrame:CGRectMake(250-itemTextSize.width,0,itemTextSize.width+15, textHeight)];
[cell.contentView addSubview:messageTextview];
messageTextview.editable=NO;
messageTextview.text = messageText;
messageTextview.dataDetectorTypes=UIDataDetectorTypeAll;
messageTextview.textAlignment=NSTextAlignmentJustified;
messageTextview.font=[UIFont fontWithName:#"Helvetica Neue" size:13.0];
messageTextview.backgroundColor=[UIColor clearColor];
messageTextview.tag=indexPath.row;
cell.Avatar_Image.image=[UIImage imageNamed:#"avatar.png"];
cell.time_Label.text=data.messageTime;
cell.selectionStyle=UITableViewCellSelectionStyleNone;
messageTextview.scrollEnabled=NO;
return cell;
}
else{
CustomCell2 *cell = (CustomCell2 *)[self.tableview dequeueReusableCellWithIdentifier:CellIdentifier2];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"CustomCell2" owner:self options:nil];
cell = [topLevelObjects objectAtIndex:0];
}
UIImageView *bubbleImage=[[UIImageView alloc] initWithImage:[[UIImage imageNamed:#"chatbubble"] stretchableImageWithLeftCapWidth:15 topCapHeight:15]];
[cell.contentView addSubview:bubbleImage];
[bubbleImage setFrame:CGRectMake(50,5, itemTextSize.width+10, textHeight)];
bubbleImage.tag=56;
UITextView *messageTextview=[[UITextView alloc]initWithFrame:CGRectMake(50,0,itemTextSize.width+15, textHeight)];
[cell.contentView addSubview:messageTextview];
messageTextview.editable=NO;
messageTextview.text = messageText;
messageTextview.dataDetectorTypes=UIDataDetectorTypeAll;
messageTextview.textAlignment=NSTextAlignmentJustified;
messageTextview.backgroundColor=[UIColor clearColor];
messageTextview.font=[UIFont fontWithName:#"Helvetica Neue" size:13.0];
messageTextview.scrollEnabled=NO;
messageTextview.tag=indexPath.row;
cell.Avatar_Image.image=[UIImage imageNamed:#"avatar"];
cell.time_Label.text=feed_data.messageTime;
cell.selectionStyle=UITableViewCellSelectionStyleNone;
return cell;
}
}
For Height:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
float cellHeight;
// text
NSString *messageText = #"Your text";
//
CGSize boundingSize = CGSizeMake(messageWidth-20, 10000000);
CGSize itemTextSize = [messageText sizeWithFont:[UIFont systemFontOfSize:14]
constrainedToSize:boundingSize
lineBreakMode:NSLineBreakByWordWrapping];
// plain text
cellHeight = itemTextSize.height;
if (cellHeight<25) {
cellHeight=25;
}
return cellHeight+30;
}
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.
this is what I am trying to do. I have a UILabel, but one word in that UILabel should be in a red color. After some research I found the TTTAttributedLabel
But I can't get my head arround it. Because my label is multilanguage so it's quite difficult because they are all working with NSRange.
Here is my label.
In dutch:
Het 25m bad is vandaag **bezet** van 12:00 tot 15:00
In English
The 25m pool is today **occupied** from 12:00 till 15:00
I need the text in bold in the red color.
Can anybody help me?
Kind regards
For example, you could use this snippet to get the NSRange where "occupied" or "bezet" is:
NSRange occupiedRange = [str rangeOfString:NSLocalizedString(#"occupied", #"")];
if (occupiedRange.location == NSNotFound) {
NSLog(#"Not found");
} else {
...
}
Hope the below code snippet may work for you
-(NSAttributedString*)configureToAttributedwithString:(NSString*)str
{
NSRange occupiedRange = [str rangeOfString:NSLocalizedString(#"occupied", #"")];
if (occupiedRange.location == NSNotFound)
{
NSLog(#"Not found");
NSAttributedString *attRStr = [[[NSAttributedString alloc] initWithString:str] autorelease];
return (attRStr);
}
else
{
NSString *string = [str substringToIndex:occupiedRange.location];
str = [str substringFromIndex:occupiedRange.location];
NSString *tarGetString = [str substringToIndex:occupiedRange.length];
str = [str substringFromIndex:occupiedRange.length];
CGColorRef colorRed = [[UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1.0] CGColor];
NSNumber *underline = [NSNumber numberWithInt:kCTUnderlineStyleSingle];
CTFontRef sysUITargetFont = CTFontCreateUIFontForLanguage(kCTFontUIFontEmphasizedSystem,20.0, NULL);
NSDictionary *attributesDictTarget = [NSDictionary dictionaryWithObjectsAndKeys:
(id)underline, (id)kCTUnderlineStyleAttributeName,
colorRed, (id)kCTForegroundColorAttributeName,
colorRed, (id)kCTStrokeColorAttributeName,nil];
CGColorRef colorBlack = [[UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0] CGColor];
CTFontRef sysUIDefaultFont = CTFontCreateUIFontForLanguage(kCTFontUIFontMessage,20.0, NULL);
NSDictionary *attributesDictDefault = [NSDictionary dictionaryWithObjectsAndKeys:
colorBlack, (id)kCTStrokeColorAttributeName,nil];
NSMutableAttributedString *attMString = [[NSMutableAttributedString alloc] initWithString:string attributes:attributesDictDefault];
NSAttributedString *stringToDraw = [[NSAttributedString alloc] initWithString:tarGetString
attributes:attributesDictTarget];
[attMString appendAttributedString:stringToDraw];
NSAttributedString *stringRest = [[NSAttributedString alloc] initWithString:str
attributes:attributesDictDefault];
[attMString appendAttributedString:stringRest];
NSLog(#"check %#", [attMString string]);
return (attMString);
}
}
is it possible to populate the UIPickerView data dynamically from external XML file.
For example, I will have TextA, TextB and TextC in my picker view and I have the same in my XML file in remote server. I have successfully developed reading the XML data from remote server and displaying the text (they were title and url) in my tableview. But now I am trying to populate my UIPickerView data from my XML file. The main purpose of this is to dynamically control the UIPickerView data from my XML file.
Is there anyway to make this happen?
You can parse XMl files with NSXMLParser. It's an event driven parser, so you have to set up a delegate to handle all the callbacks and create your arrays and dictionaries from the parsed nodes.
You could also use a class like XMLReader. This allows you to simply pass your xml as an NSData or NSString object and get a parsed NSDictionary. You can then use that to populate the UIPickerView.
It's a bit inconvenient though and it would be a better choice to use .plist files, if you can. Of course that's not an option, if you want to access the same information from other platforms too.
Then, all you would have to do after downloading the file is:
NSArray *onlineList = [plistAsString propertyList];
Or if you download the file onto disk:
NSArray *onlineList = [[NSArray alloc] initWithContentsOfFile:pathToPlistFile];
// release if not using ARC.
I have done the following to display the title and url in one of my apps. I want the same to populate the picker data instead of table cell:
This is a link of one of my apps which demonstrates the implementation of the following code:
urlString = #"http://jeewanaryal.web44.net/iPhoneXML/nepaliMoviesNews.xml";
data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
dict = [XMLReader dictionaryForXMLData:data error:nil];
newsItems = [[NSMutableArray alloc] initWithArray:[[[dict objectForKey:#"list"] objectForKey:#"lists"] objectForKey:#"news"]];
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
CustomCell *cell= [[CustomCell alloc] initWithFrame:CGRectMake(0, 0, 300, 60)];
// Default to no selected style and not selected
cell.selectionStyle = UITableViewCellSelectionStyleNone;
// Set the image for the cell
[cell setTheImage:[UIImage imageNamed:[NSString stringWithFormat:#"Arrow3.png"]]];
NSMutableArray *temp = [[NSMutableArray alloc] init];
for (NSDictionary *fruitDict in newsItems) {
//UILabel *songTitle = [[UILabel alloc] initWithFrame:CGRectMake(40, 200, 300, 40)];
[temp insertObject:[NSString stringWithFormat:#"%#",[[fruitDict objectForKey:#"title"] objectForKey:#"text"]]
atIndex:0];
//cell.textLabel.text = [NSString stringWithFormat:#"%#",[[fruitDict objectForKey:#"title"] objectForKey:#"text"]];
//[self.view addSubview:songTitle];
}
//NSLog(#"\n\n temp: \n %#",temp);
cell.textLabel.text = [temp objectAtIndex:indexPath.row];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.textLabel.font = [UIFont fontWithName:#"Gill Sans" size:20];
cell.textLabel.textColor = [UIColor colorWithRed:102.0/255 green:204.0/255 blue:170.0/255 alpha:1];
//cell.textLabel.textColor =[UIColor colorWithRed:(CGFloat)0.24 green:(CGFloat)0.7 blue:(CGFloat)0.45 alpha:(CGFloat)1];
cell.backgroundColor = [UIColor blackColor];
[[cell textLabel] setTextAlignment:UITextAlignmentLeft];
//cell.textLabel.adjustsFontSizeToFitWidth = YES;
//cell.detailTextLabel.numberOfLines = 2;
return cell;
}
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.