Как сделать прокрутку табличного представления - PullRequest
1 голос
/ 10 октября 2011

Как сделать прокручиваемый UITableView?
Когда я прокручиваю вниз или прокручиваю вверх за пределами области просмотра таблицы, приложение вполне. Я использую класс tablehandler для моего источника данных табличного представления. Вот некоторый код из моего класса tablehandler.

//  TableHandler.h
#import <Foundation/Foundation.h>
@interface TableHandler : NSObject <UITableViewDelegate, UITableViewDataSource>
{
    NSMutableArray * tableDataList;
    //database variables
    NSString *databaseName;
    NSString *databasePath; 
}

@property (nonatomic, retain) NSMutableArray * tableDataList;
- (void) fillList;
- (void) dbPathInit;
- (void) getAllPhysician;
@end

//  TableHandler.m
#import "TableHandler.h"
#import "DoctorItem.h"
#import "DoctorItem.h"
#import <sqlite3.h>
@implementation TableHandler
@synthesize tableDataList;
- (void) fillList { 
    [self dbPathInit];
    [self getAllPhysician]; 
}
-(void)dbPathInit{
    databaseName=@"clinic_directory.db";
    NSArray *documentPaths=
    NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES); 
    NSString *documentsDir=[documentPaths objectAtIndex:0];
    databasePath=[documentsDir stringByAppendingPathComponent:databaseName];
}
-(void)getAllPhysician{
    sqlite3 *database;
        self.tableDataList=[[NSMutableArray alloc]init];
    if(sqlite3_open([databasePath UTF8String],&database)==SQLITE_OK){
        const char *sqlStatement="select d._id, d.title, d.name dname, qualification, c.name cname from doctor d left join category_doctor cd ON cd.doctor_id=d._id LEFT JOIN category c on c._id=cd.category_id order by d.name asc";
        sqlite3_stmt *compiledStatement;
        if (sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL)==SQLITE_OK) {(sqlite3_step(compiledStatement)==SQLITE_ROW) {
                NSInteger doctorId=(int)sqlite3_column_int(compiledStatement,0);
                NSString *doctorTitle=[NSString stringWithUTF8String:(char*)sqlite3_column_text(compiledStatement, 1)];
                NSString *doctorName=[NSString stringWithUTF8String:(char*)sqlite3_column_text(compiledStatement, 2)];
                NSString *qualification=[NSString stringWithUTF8String:(char*)sqlite3_column_text(compiledStatement,3)];
                NSString *category=[NSString stringWithUTF8String:(char*) sqlite3_column_text(compiledStatement,4)];
                DoctorItem *physician=[[DoctorItem alloc]initWithId:doctorId Title:doctorTitle DName:doctorName Qualifications:qualification CName:category];
                [self.tableDataList addObject:physician];
                [physician release];            
            }
        }
        sqlite3_finalize(compiledStatement);
    }
    sqlite3_close(database);
}
- (NSInteger) tableView : (UITableView *) tableView numberOfRowsInSection: (NSInteger) section {
    return [self.tableDataList count];
}
-(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];
    }
    DoctorItem *physician=(DoctorItem*)[tableDataList objectAtIndex:indexPath.row];

    UILabel *lbName=[[UILabel alloc] initWithFrame:CGRectMake(10, 10, 290, 25)];
    [lbName setText:physician.DName];
    [cell.contentView addSubview:lbName];
    [lbName release];
    UILabel *lbQualifications=[[UILabel alloc]initWithFrame:CGRectMake(10,40,290,25)];
    [lbQualifications setText:physician.Qualifications];
    lbQualifications.textColor=[UIColor lightGrayColor];
    [cell.contentView addSubview:lbQualifications]; 
    [lbQualifications release];
    UILabel *lbCategory=[[UILabel alloc]initWithFrame:CGRectMake(10,70,290,25)];
    [lbCategory setText:physician.CName];
    lbCategory.textColor=[UIColor lightGrayColor];
    [cell.contentView addSubview:lbCategory];
    [lbCategory release];
    [physician release];
    return cell;
}
-(CGFloat)tableView :(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath{
    return 100;
}
- (void)dealloc {
    [tableDataList release];
    [super dealloc];
}
@end

Ответы [ 3 ]

4 голосов
/ 10 октября 2011

UITableView является подклассом UIScrollView. Он будет прокручиваться для вас автоматически.

Вашему UITableView потребуется объект источника данных для подачи данных. Если число или строки из источника данных больше, чем может уместиться на экране, таблица будет прокручиваться.

Если вы хотите программно прокрутить таблицу, вы можете использовать свойство смещения в UIScrollView или один из методов в UITableView, чтобы сделать это.

http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UITableView_Class/Reference/Reference.html

http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UIScrollView_Class/Reference/UIScrollView.html

3 голосов
/ 10 октября 2011

Когда вы увеличиваете количество строк таблицы, оно автоматически прокручивается.Нет необходимости включать дополнительные свойства для просмотра таблицы.

Например:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 10;
}
1 голос
/ 10 октября 2011

Вы не можете сделать это прокруткой, установив свойство или около того. Посмотрите протоколы UITableviewDataSource и UITableviewDelegate. Реализуя эти сообщения, вы предоставляете данные для табличного представления, а затем они автоматически прокручиваются по мере необходимости.

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