Reputation: 6490
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.
Upvotes: 1
Views: 73
Reputation: 6192
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
Upvotes: 1
Reputation: 577
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];
Upvotes: 0