Добавление HTML-файлов в табличное представление в Xcode - PullRequest
0 голосов
/ 27 января 2012

Я очень новичок в программировании на iOS.В настоящее время я работаю над приложением, использующим раскадровку, и хочу иметь возможность отображать серию из 7 файлов HTML в таблице, которая при нажатии на каждый из них затем отображает файл HTML с форматированным текстом.

Я погуглил до края земли и обратно и не могу найти ничего, что ответило бы на мой вопрос о том, как этого добиться.

В основном приложение имеет 4 вкладки, первая - текстовая, вторая - та, где яхочу отображать html-файлы в таблице (называемой Toolbox), третий - это веб-браузер, а последний - текстовый.

Я почти уверен, что у меня есть контроллеры представления там, где они должны быть, но при загрузке htmlфайлов в таблицу не происходит.Я не получаю никаких ошибок при сборке, я просто получаю пустое табличное представление на вкладке при запуске приложения в симуляторе.

Я не уверен, какую другую информацию мне нужно предоставить, чтобы кто-нибудь помог- ниже приведен список соответствующих файлов и код из соответствующих файлов h / m.(Я пока не могу публиковать изображения)

Буду признателен за любую помощь или совет

Список файлов:

AppDelegate.h

AppDelegate.m

globals.h

MainStoryboard_iPhone.storyboard

MainStoryboard_iPad.storyboard

ToolboxViewController.h

ToolboxViewController.m

chapter1.html

chapter2.html

chapter3.html

chapter4.html

chapter5.html

chapter6.html

chapter7.html

AppDelegate.h содержит следующее:

#import < UIKit/UIKit.h>
NSInteger articleIndex;
@interface AppDelegate : UIResponder < UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end

AppDelegate.m содержит следующее:

#import "AppDelegate.h"
#import "ToolboxViewController.h"
@implementation AppDelegate {
NSArray *articleList;
}
@synthesize window = _window;
- (void)dealloc
{
[_window release];
[super dealloc];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:         (NSDictionary *)launchOptions
{
articleList = [[NSArray arrayWithObjects:
                @"chapter1",
                @"chapter2",
                @"chapter3",
                @"chapter4",
                @"chapter5",
                @"chapter6",
                @"chapter7",
                nil] retain];

return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
/*
 Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
 Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
 */
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
/*
 Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
 If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
 */
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
/*
 Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
 */
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
/*
 Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
 */
}

- (void)applicationWillTerminate:(UIApplication *)application
{
/*
 Called when the application is about to terminate.
 Save data if appropriate.
 See also applicationDidEnterBackground:.
 */
}

@end

globals.h содержит следующее:

#ifndef TabAT_globals_h
#define TabAT_Viewer_globals_h
NSInteger articleIndex;
#endif

ToolboxViewController.h содержит следующее:

#import <UIKit/UIKit.h>
#import "globals.h"
@interface ToolboxViewController : UITableViewController 
{   
NSArray *articleList;
NSArray *articleNames;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UINavigationController *navigationController; 
@end

ToolboxViewController.m содержит следующее:

#import "ToolboxViewController.h"
#import "globals.h"
@implementation ToolboxViewController
@synthesize window = _window;
@synthesize navigationController = _navigationController;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
    // Custom initialization
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];

// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];

articleNames = [[NSArray arrayWithObjects:
                @"chapter1",
                @"chapter2",
                @"chapter3",
                @"chapter4",
                @"chapter5",
                @"chapter6",
                @"chapter7",
                nil] retain];
articleList = [[NSArray arrayWithObjects:
                @"What is Anxiety",
                @"Anxiety Symptoms",
                @"Coping Skills",
                @"Visualisation",
                @"Treatment",
                @"Places to go for help",
                @"About",
                nil] retain];


// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;

// Uncomment the following line to display an Edit button in the navigation bar for this    view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return YES;
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1; 
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [articleList count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"ToolboxCell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}

// Configure the cell...

cell.textLabel.text = [articleList objectAtIndex:indexPath.row];

return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
    // Delete the row from the data source
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}   
else if (editingStyle == UITableViewCellEditingStyleInsert) {
    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}   
}
*/
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the item to be re-orderable.

return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here. Create and push another view controller.
/*
 <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
 // ...
 // Pass the selected object to the new view controller.
 [self.navigationController pushViewController:detailViewController animated:YES];
 [detailViewController release];
 */

1 Ответ

0 голосов
/ 27 января 2012

Ваша реализация ToolboxViewController.m не завершена. В вашем коде оба значения numberOfSectionsInTableView: и numberOfRowsInSection: возвращают 0, поэтому в вашей таблице ничего не отображается. Из того, что я могу сказать об описании вашего приложения, они должны возвращать 1 и длину вашего массива articleList соответственно. Также вам нужно будет установить содержимое ячеек таблицы в cellForRowAtIndexPath:.

Вы можете сделать что-то вроде следующего:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{ 
    return 1; 
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [articleList length]; 
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 
    }

    // here's where you set the content inside your table cell
    cell.textLabel.text = [articleList objectAtIndex:[indexPath row]];

    return cell;
}

Этого должно быть достаточно, чтобы начать.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...