I am developing iPhone app, in which i got stuck at one point,
what i want to do is, i have UITableView and in the UITableViewCell i want to display the text like this:
India in Country23
Australia in Country2
USA in Country22
AMERI in Country26
FRANCE in Country12
ITALY in Country20
WEST INDIES in Country42
KENYA
SOUTH AFRICA
NEW ZEALAND
The text before in is in one array and text after in (which is in BOLD) is in another array and also i want to change the text color of BOLD text which is after in
Note: Some of the cell contains bold text and some doesn't
How to display data like this in UITableVIew ?
please help and thanks in advance.
Here is a complete example
#implementation MyTableViewController
{
NSArray *_countryNames;
NSArray *_countryNumbers;
}
- (void)viewDidLoad
{
_countryNames = #[#"India", #"Australia", #"USA"];
_countryNumbers = #[#"Country23", #"Country2", #"Country22"];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return MIN(_countryNames.count, _countryNumbers.count);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
static NSString *identifier = #"reuseIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (!cell)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier: identifier];
}
NSString *text1 = _countryNames[indexPath.row];
NSString *text2 = _countryNumbers[indexPath.row];
NSString *completeText = [[text1 stringByAppendingString:#" " ] stringByAppendingString:text2];
const CGFloat fontSize = 13;
UIFont *boldFont = [UIFont boldSystemFontOfSize:fontSize];
UIFont *regularFont = [UIFont systemFontOfSize:fontSize];
NSDictionary *attrs = #{NSFontAttributeName : regularFont};
NSDictionary *subAttrs = #{NSFontAttributeName : boldFont};
NSRange range = NSMakeRange(text1.length + 1, text2.length);
NSMutableAttributedString *attributedText =
[[NSMutableAttributedString alloc] initWithString:completeText
attributes:attrs];
[attributedText setAttributes:subAttrs range:range];
[cell.textLabel setAttributedText:attributedText];
return cell;
}
#end
I think you need to use custom uilabel with NSAttributedString or an NSMutableAttributedString functionality like this example
NSString *boldFontName = [[UIFont boldSystemFontOfSize:12] fontName];
NSString *yourString = ...;
NSRange boldedRange = NSMakeRange(22, 4);
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:yourString];
[attrString beginEditing];
[attrString addAttribute:kCTFontAttributeName
value:boldFontName
range:boldedRange];
[attrString endEditing];
[_label setAttributedText:attrString];
Related
I am bit trouble with setting attributed text to uilable which is defined in uitableview cell. I am setting attributed text in cellForRowAtIndexPath delegate method of uitableview but it does not affect on output. I just wanted text of uilabel will display as bold text.
My code is as follow:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
MessagesTable *msgobject=[messages objectAtIndex:indexPath.row];
static NSString* cellIdentifier = #"messagingCellText";
TextTableViewCell *ccell = (TextTableViewCell*) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (ccell == nil)
{
ccell = [[TextTableViewCell alloc] initMessagingCellWithReuseIdentifier:cellIdentifier MessageType:msgobject.messageMediaType];
cell2.backgroundColor=[UIColor clearColor];
cell2.userInteractionEnabled=YES;
cell2.layer.shouldRasterize = YES;
cell2.layer.rasterizationScale = [UIScreen mainScreen].scale;
}
NSString *newString = "This is Bold, This is regular";
NSMutableAttributedString* attrStr = [[NSMutableAttributedString alloc]initWithString:newString];
NSRange rangeOfSubstring = [newString rangeOfString:#"This is Bold"];
[attrStr addAttribute:NSFontAttributeName
value:[UIFont fontWithName:#"GandhiSans-Bold" size:16]
range:rangeOfSubstring];
ccell.messageLabel.attributedText = attrStr;
return ccell;
}
And my initMessagingCellWithReuseIdentifier: method is as follows:
-(id)initMessagingCellWithReuseIdentifier:(NSString*)reuseIdentifier MessageType:(NSString *)msgTypePara{
if (self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier]) {
/*Message-Label*/
self.messageLabel = [[UILabel alloc] initWithFrame:CGRectZero];
self.messageLabel.backgroundColor = [UIColor clearColor];
//self.messageLabel.font = [UIFont systemFontOfSize:messageTextSize];
self.messageLabel.lineBreakMode = NSLineBreakByWordWrapping;
self.messageLabel.numberOfLines = 0;
self.messageLabel.textColor=[UIColor blackColor];
self.messageLabel.textAlignment=NSTextAlignmentLeft;
//self.messageLabel.font=[UIFont preferredFontForTextStyle:UIFontTextStyleBody];
//self.messageLabel.font = [UIFont fontWithName:#"GandhiSans-regular" size:messageTextSize];
self.messageLabel.userInteractionEnabled=YES;
[self.messageLabel sizeToFit];
[self addSubview: self.messageLabel];
[self.contentView addSubview: self.messageView];
return self;
}
Try this:
NSMutableAttributedString *MylabelAttributes = [[NSMutableAttributedString alloc] initWithString:#"my test"];
[MylabelAttributes addAttribute:NSForegroundColorAttributeName value:[UIColor yourcolor] range:NSMakeRange(0,MylabelAttributes.length)];
[MylabelAttributes addAttribute:NSFontAttributeName
value:[UIFont boldSystemFontOfSize:19.0]
range:NSMakeRange(0,MylabelAttributes.length)];
self.yourlabel.attributedText=MylabelAttributes;
try this
and please replace it with your particular code and check is there any change happens
NSString *newString = #"This is Bold, This is regular";
NSMutableAttributedString* attrStr = [[NSMutableAttributedString alloc]initWithString:newString];
NSRange rangeOfSubstring = [newString rangeOfString:#"This is Bold"];
[attrStr addAttribute:NSFontAttributeName
value:[UIFont fontWithName:#"TimesNewRomanPS-BoldMT" size:16]
range:rangeOfSubstring];
[attrStr addAttribute:NSForegroundColorAttributeName
value:[UIColor redColor]
range:rangeOfSubstring];
I want to merge NSString and NSMutableAttributedString .
In below code i want to make self.txtSearch as custom bold size and color.
code -
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
SearchViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"SearchViewCell"];
AutoSuggestModel *autoSuggestModel = [self.autoSuggestArray objectAtIndex:indexPath.row];
if ([[autoSuggestModel type] isEqualToString:#"product"] || [[autoSuggestModel type] isEqualToString:#"category"]){
cell.lblText.text = [NSString stringWithFormat:#"%# in %#", self.txtSearch , [autoSuggestModel label]] ;
}else{
cell.lblText.text = [autoSuggestModel label];
}
return cell;
}
I could make bold particular string with below code. but i want to append both string.
NSMutableAttributedString *boldString = [[NSMutableAttributedString alloc] initWithString:self.txtSearch];
NSRange boldRange = [[autoSuggestModel label] rangeOfString:self.txtSearch];
[boldString addAttribute: NSFontAttributeName value:[UIFont boldSystemFontOfSize:16] range:boldRange];
[cell.lblText setAttributedText: boldString];
update you method like bellow
if ([[autoSuggestModel type] isEqualToString:#"product"] || [[autoSuggestModel type] isEqualToString:#"category"]){
cell.textLabel.attributedText = [self getBoldText:cell withSearch:#"search text" withAutoSuggestModel:#"autoSuggestModel"];
}else{
cell.lblText.text = [autoSuggestModel label];
}
//check above code by the following method
-(NSMutableAttributedString*)getBoldText:(UITableViewCell*)cell withSearch:(NSString*)searchText withAutoSuggestModel:(NSString*)autoSuggestModelText{
NSString *title = [NSString stringWithFormat:#"%# in %#", searchText,autoSuggestModelText];
cell.textLabel.text = title;
UIColor *color = [UIColor redColor];
UIFont *font = [UIFont boldSystemFontOfSize:16];
NSDictionary *attrs = #{NSForegroundColorAttributeName : color,NSFontAttributeName:font};
NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithAttributedString:cell.textLabel.attributedText];
[attrStr addAttributes:attrs range:[title rangeOfString:autoSuggestModelText]];
return attrStr;
}
A very cursory look at the NSString documentation has a section called "combining strings" and a method called stringByAppendingString:
Using this method, it should be incredibly straight-forward to accomplish what you're trying to do.
NSMutableAttributedString *boldString = [[NSMutableAttributedString alloc]
initWithString:[self.txtSearch stringByAppendingString:yourMutableString]];
I try to display a checkmark symbol like this:
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.alignment = NSTextAlignmentCenter;
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
[#"✓" drawInRect: CGRectInset(ovalRect, 0/116.0*width, 11/116.0*width) withAttributes:[NSDictionary dictionaryWithObjects:#[[UIFont fontWithName: #"HelveticaNeue" size: 80.0/116.0*width], paragraphStyle, [UIColor orangeColor]] forKeys:#[NSFontAttributeName, NSParagraphStyleAttributeName, NSForegroundColorAttributeName]]];
On http://iosfonts.com the symbol looks just like I want it for Helvetica Neue. However, on the device/ simulator it looks completely different. I found about 3 fonts where it looked different but for the other 20 fonts I tested it always looked the same, always different from http://iosfonts.com. How can I find out how the checkmark symbol would look in different iOS fonts? I don't want to try them all out by hand.
If someone else has font problems, here is the code to display text in all available fonts in an UITableView.
- (void)viewDidLoad
{
[super viewDidLoad];
//Fill NSMutableArray fonts with all available fonts
fonts = [NSMutableArray array];
NSArray *familyNames = [[NSArray alloc] initWithArray:[UIFont familyNames]];
NSArray *fontNames;
NSInteger indFamily, indFont;
for (indFamily = 0; indFamily < [familyNames count]; ++indFamily)
{
fontNames = [[NSArray alloc] initWithArray:[UIFont fontNamesForFamilyName:[familyNames objectAtIndex:indFamily]]];
for (indFont = 0; indFont < [fontNames count]; ++indFont)
{
[fonts addObject:[fontNames objectAtIndex:indFont]];
}
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
NSString *font = [fonts objectAtIndex:indexPath.row];
[cell.textLabel setText:[NSString stringWithFormat:#"✓ %#", font]];
[cell.textLabel setFont:[UIFont fontWithName:font size:16]];
return cell;
}
I want to be able to change the text in my UITableView cells when they are tapped on (selected/highlighted). The content from each cell is derived from an NSAttributedString. Here is that code:
-(NSAttributedString*)formattedSubject:(int)state {
if(formattedSubject!=nil) return formattedSubject;
NSDictionary *boldStyle = [[NSDictionary alloc] init];
if(state==1) {
boldStyle = #{NSFontAttributeName:[UIFont fontWithName:#"Helvetica-Bold" size:16.0],NSForegroundColorAttributeName:[UIColor colorWithRed:0.067 green:0.129 blue:0.216 alpha:1.0]};
}
else {
boldStyle = #{NSFontAttributeName:[UIFont fontWithName:#"Helvetica-Bold" size:16.0],NSForegroundColorAttributeName:[UIColor whiteColor]};
}
NSDictionary* normalStyle = #{NSFontAttributeName: [UIFont fontWithName:#"Helvetica" size:14.0]};
NSMutableAttributedString* articleAbstract = [[NSMutableAttributedString alloc] initWithString:subject];
[articleAbstract setAttributes:boldStyle range:NSMakeRange(0, subject.length)];
[articleAbstract appendAttributedString:[[NSAttributedString alloc] initWithString:#"\n"]];
int startIndex = [articleAbstract length];
NSTimeInterval _interval=[datestamp doubleValue];
NSDate *date = [NSDate dateWithTimeIntervalSince1970:_interval];
NSDateFormatter *_formatter=[[NSDateFormatter alloc]init];
[_formatter setDateFormat:#"MM/dd/yy"];
NSString* description = [NSString stringWithFormat:#"By %# on %#",author,[_formatter stringFromDate:date]];
[articleAbstract appendAttributedString:[[NSAttributedString alloc] initWithString: description]];
[articleAbstract setAttributes:normalStyle range:NSMakeRange(startIndex, articleAbstract.length - startIndex)];
formattedSubject = articleAbstract;
return formattedSubject;
}
As you can see, I would like the boldStyle text to be a certain color (given by [UIColor colorWithRed:0.067 green:0.129 blue:0.216 alpha:1.0]) when the state is "1", and white otherwise. I've currently tried the following modifications in cellForRowAtIndexPath, as well as didSelectRowAtIndexPath:
cellForRowAtIndexPath:
NSIndexPath *path = [tableView indexPathForSelectedRow];
if(path) {
cell.textLabel.attributedText = [news formattedSubject:1];
}
else {
cell.textLabel.attributedText = [news formattedSubject:0];
}
What I am doing here is checking if a cell is selected, and if so then I changed that cell's "attributedText" to the "0" format. However, this didn't work, and I suspected it was because the modification had to be made when the cell was actually selected. So I tried the following in didSelectRowAtIndexPath:
didSelectRowAtIndexPath:
News *news = newsArray[indexPath.row];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.textLabel.attributedText = [news formattedSubject:0];
However, it seems like the change is never made. I put an NSLog in the "else" part of the boldStyle if/else statement, and it was never written to the console.
Neither of my attempts at a solution have worked, and I've run out of ideas. How can I get the NSAttributedString to change when a cell is highlighted?
Update: It's also interesting that normalStyle text, which is by default black, does turn white when the cell is highlighted/selected when I add cell.textLabel.highlightedTextColor = [UIColor whiteColor]; in cellForRowAtIndexPath, but boldStyle text does not.
I have problem the same, and..
cell.textLabel.enable = NO;
It just resolved
In your cellForRowAtIndexPath method you are checking if a selectedIndexPath in this tableView exists.
NSIndexPath *path = [tableView indexPathForSelectedRow];
if(path) {
I think you want to compare your indexPath and your selectedIndexPath. You should use isEqual: for that.
NSIndexPath *selectedIndexPath = [tableView indexPathForSelectedRow];
if([selectedIndexPath isEqual:indexPath]) {
I want to make sl.asl bold in the below and colour it based on it's numeric value in the below. Any ideas?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateStyle:NSDateFormatterShortStyle];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
// Configure the cell...
ServiceLevel *sl = (ServiceLevel *)[self.importedRows objectAtIndex:indexPath.row];
cell.textLabel.text = [NSString stringWithFormat:#"%# - %#", sl.name , sl.asl];
return cell;
}
An NSAttributedString ought to do the trick.
Like:
NSString *name = #"SampleName";
NSUInteger asl = 2;
NSString *t_string = [NSString stringWithFormat:#"%# - %d", name , asl];
NSUInteger t_nameLength = name.length;
NSUInteger t_aslLength = 1;
UIColor *t_color = nil;
switch (asl) {
case 1:
t_color = [UIColor redColor];
break;
case 2:
t_color = [UIColor greenColor];
break;
default:
t_color = [UIColor blackColor];
break;
}
NSMutableAttributedString *t_attributedString = [[NSMutableAttributedString alloc] initWithString:t_string];
[t_attributedString addAttribute:NSFontAttributeName value:[UIFont fontWithName:#"Arial" size:14.0] range:NSMakeRange(0, t_nameLength)];
[t_attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, t_nameLength)];
[t_attributedString addAttribute:NSFontAttributeName value:[UIFont fontWithName:#"Arial-BoldMT" size:14.0] range:NSMakeRange(t_nameLength + 3, t_aslLength)];
[t_attributedString addAttribute:NSForegroundColorAttributeName value:t_color range:NSMakeRange(t_nameLength + 3, t_aslLength)];
cell.textLabel.attributedText = t_attributedString;
Create an NSAttributedString and assign it to cell.textLabel.attributedText. For example:
NSDictionary *attributes = #{
NSForegroundColorAttributeName:[UIColor redColor],
NSFontAttributeName:[UIFont fontWithName:#"Helvetica-Bold" size:16]
};
NSString *delimiter = #" - ";
NSString *text = [NSString stringWithFormat:#"%#%#%#", sl.name, delimiter, sl.asl];
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:text];
[attributedText addAttributes:attributes range:NSMakeRange(sl.name.length + delimiter.length, sl.asl.length)];
cell.textLabel.attributedText = attributedText;
UPDATED CODE - for bolding a part of a text and changing the colour based on a numeric value
Please d some initial research before you post questions on stackoverflow, and show us what you've tried in the past so that we can help you accordingly.
You can set a part of your text to bold by using the NSAttributedString:
//To bold a part of a string you have to let it know where you want the bold to start and end from, for that you need to know the length of your sl.asl variable
NSMutableAttributedString * attributedAsl = [[NSMutableAttributedString alloc] initWithAttributedString:sl.asl];
NSString *delimiter = #" - "; //This is what will be written to separate sl.name and sl.asl
NSString *begginingString = [NSString stringWithFormat:#"%#%#", delimiter, sl.name];
//What we dont want bolded
NSInteger startBoldFromEndOfBeginningString = [begginingString length];
//The length of text we want bolded - your sl.asl variable
NSInteger slAslLength = ((NSString)sl.asl).length;
UIFont *font= [UIFont fontWithName:#"Helvetica-Bold" size:25.0f];
[attributedAsl addAttribute:NSFontAttributeName value:font range:NSMakeRange(startBoldFromEndOfBeginningString, slAslLength)];
cell.textLabel.attributedText = attributedAsl;
And then you can set the text color like so
cell.textLabel.textColor = [UIColor redColor];
Now if you want to change the textColor based on the numeric value of something you then have to start playing with RGB values which make up color values.
[UIColor colorWithRed:1.0 green:0.0 blue:1.0 alpha:1.0];
What will be helpful to ensure an even distribution of colors to the desired range of colours would be to know the highest the number can go to.
Lets say you are displaying the alphabet of the english language in a tableView, the total number of cells would be 26, and you want to change the color of text for each cell displayed, one solution would be to do this:
CGFloat maxNumber = 26; //total number of letters
CGFloat dynamicColor = 1.0/maxNumber * indexPath.row;
[UIColor colorWithRed:dynamicColor green:0.0 blue:1.0 alpha:1.0];
this will ensure that each textColor is different for each cell that is displayed.