Johan Grip Johan Grip - 1 month ago 6
iOS Question

Populate a detail view with (correct) txt-file

I have a tableview with country names. When a cell is tapped I want it to move to a detail view with text about the country. I have a separate txt-file for each country with the same name as the title in the cell (e.g. USA.txt).

How do I display these txt-files in the detail view?

My code so far looks like this:

TableViewController.h

@property (nonatomic, strong) NSArray *Title;


TableViewController.m

- (void)viewDidLoad {
[super viewDidLoad];

_Title = @[@”Afganistan”,
@”Albania”,
@”Algeria”,

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"TableCell";
TableCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

int row = [indexPath row];

cell.TitleLabel.text = _Title[row];

return cell;
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

if ([[segue identifier] isEqualToString:@"ShowDetails"]) {
DetailViewController *detailviewcontroller = [segue destinationViewController];

NSIndexPath *myIndexPath = [self.tableView indexPathForSelectedRow];

int row = [myIndexPath row];
detailviewcontroller.DetailModal = @[_Title[row]];
}
}


DetailViewController.h

@property (strong, nonatomic) IBOutlet UILabel *TitleLabel;

@property (strong, nonatomic) NSArray *DetailModal;


DetailViewController.m

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.

_TitleLabel.text = _DetailModal[0];

self.navigationItem.title = _DetailModal[0];

}


I found the code below here on StackOverflow but I don’t know how to implement it.

NSString *path = [[NSBundle mainBundle]pathForResource:@”Afganistan” ofType:@"txt"];
NSString *content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];

Answer

You need can take one more UILabel(say detailLabel) to display the content of .txt files. In ViewDidLoad of DetailViewController, add below lines

NSString *path = [[NSBundle mainBundle]pathForResource:_DetailModal[0] ofType:@"txt"];
NSString *content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
self.detailLabel.text = content
self.detailLabel.numberOflines = 0
Comments