2014-01-10 7 views
0

UIlabel 대신 사용자 정의 셀 무엇을 할 수 있습니까? 메서드에서 레이블이 아니라 사용자 지정 셀을 사용하고 싶습니다. 나는 사용자 정의 셀을 원한다. 그래서 나는 사용자 정의 셀에 대해 더 자세히 알지 못했다. 따라서 테이블 뷰의 레이블 대신에 사용자 정의 셀을 어떻게 사용했는지 말해 주길 바란다.사용자 정의 셀을 어떻게해야합니까?

// AppDelegate.h

#import <UIKit/UIKit.h> 

    @class ViewController; 

    @interface AppDelegate : UIResponder <UIApplicationDelegate> 

    @property (strong, nonatomic) UIWindow *window; 

    @property (strong, nonatomic) ViewController *viewController; 

    -(void)copydb; 

    @end 

// AppDelegate.m

#import "AppDelegate.h" 

    #import "ViewController.h" 

    @implementation AppDelegate 


    - (BOOL)application:(UIApplication *)application 
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
    { 
     self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] 
    bounds]]; 
     // Override point for customization after application launch. 
     self.viewController = [[ViewController alloc] 
    initWithNibName:@"ViewController" 
    bundle:nil]; 
     self.window.rootViewController = self.viewController; 
     [self.window makeKeyAndVisible]; 

     [self copydb]; 

     return YES; 
    } 


    -(void)copydb 
    { 
     NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
    NSUserDomainMask, YES); 
     NSString *documentdirectory=[paths objectAtIndex:0]; 
     NSString *inspath=[NSString stringWithFormat:@"sample.sqlite"]; 
     NSString *destpath=[documentdirectory 
    stringByAppendingPathComponent:inspath]; 
     NSString *srcpath=[[[NSBundle 
    mainBundle]resourcePath]stringByAppendingPathComponent:inspath]; 

     NSLog(@"\n srcpath= %@ \n destpath=%@",srcpath,destpath); 

     if(![[NSFileManager defaultManager]fileExistsAtPath:destpath]) 
     { 
      NSError *error; 
      NSLog(@"File not Exist"); 
      [[NSFileManager defaultManager]copyItemAtPath:srcpath 
     toPath:destpath error:&error]; 
     } 
     else 
     { 
      NSLog(@"File Exist"); 
     } 
    } 


    - (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 

//vc.h

#import <UIKit/UIKit.h> 
    #import <sqlite3.h> 
    @interface ViewController : 
           UIViewController<UITextFieldDelegate,UIAlertViewDelegate,UITableViewDataSource,UITableViewD  elegate> 
    { 
IBOutlet UITextField *fnameTxt; 
IBOutlet UITextField *lnameTxt; 
IBOutlet UITextField *addressTxt; 
IBOutlet UITextField *birthdateTxt; 
IBOutlet UITextField *cityTxt; 
IBOutlet UITableView *tbl; 

sqlite3 *db; 
NSMutableArray *data; 
    } 

    @property (atomic,retain)UILabel *label1; 
    @property (atomic,retain)UILabel *label2; 
    @property (atomic,retain)UILabel *label3; 
    @property (atomic,retain)UILabel *label4; 
    @property (atomic,retain)UILabel *label5; 

    - (IBAction)submit:(id)sender; 
    - (IBAction)update:(id)sender; 
    - (IBAction)deletes:(id)sender; 

    @end 

//vc.m

#import "ViewController.h" 

    @interface ViewController() 

    @end 

    @implementation ViewController 

    @synthesize label1; 
    @synthesize label2; 
    @synthesize label3; 
     @synthesize label4; 
    @synthesize label5; 

    - (void)viewDidLoad 
    { 
     [super viewDidLoad]; 

     data=[[NSMutableArray alloc]init]; 

     [self load]; 

    // Do any additional setup after loading the view, typically from a nib. 

    } 

    -(void)load 
    { 

[fnameTxt resignFirstResponder]; 
[lnameTxt resignFirstResponder]; 
[addressTxt resignFirstResponder]; 
[birthdateTxt resignFirstResponder]; 
[cityTxt resignFirstResponder]; 

[email protected]""; 
[email protected]""; 
[email protected]""; 
[email protected]""; 
[email protected]""; 

[data removeAllObjects]; 

NSString *insertstatement=[NSString stringWithFormat:@"select * from 
    emps"]; 
NSLog(@"%@",insertstatement); 
sqlite3_stmt *statement; 
NSString *path=[self getDBPath]; 
NSLog(@"%@",path); 

if (sqlite3_open([path UTF8String], &db)==SQLITE_OK) 
     { 
    // if (sqlite3_prepare_v2(db, [insertstatement UTF8String], -1, 
    &statement, NULL)==SQLITE_OK) 
    if (sqlite3_prepare_v2(db, [insertstatement UTF8String], -1, 
    &statement, NULL)==SQLITE_OK) 
    { 
     while (sqlite3_step(statement)==SQLITE_ROW) 
     { 
      NSMutableDictionary *record=[[NSMutableDictionary 
    alloc]init]; 

      NSString *fnm=[NSString stringWithUTF8String:(char 
    *)sqlite3_column_text(statement, 0)]; 
      NSString *lnm=[NSString stringWithUTF8String:(char 
    *)sqlite3_column_text(statement, 1)]; 
      NSString *addr=[NSString stringWithUTF8String:(char 
    *)sqlite3_column_text(statement, 2)]; 
      NSString *bDay=[NSString stringWithUTF8String:(char 
    *)sqlite3_column_text(statement, 3)]; 
      NSString *cty=[NSString stringWithUTF8String:(char 
    *)sqlite3_column_text(statement, 4)]; 

      [record setValue:fnm forKey:@"fName"]; 

      [record setValue:lnm forKey:@"lName"]; 

      [record setValue:addr forKey:@"adds"]; 

      [record setValue:bDay forKey:@"birthDay"]; 

      [record setValue:cty forKey:@"city"]; 

      [data addObject:record]; 

     } 
     sqlite3_finalize(statement); 
    } 
    sqlite3_close(db); 
     } 
     NSLog(@"Number of data in Array is = %d",[data count]); 
     [tbl reloadData]; 

    } 


    - (BOOL)textFieldShouldReturn:(UITextField *)textField 
    { 
[fnameTxt resignFirstResponder]; 
[lnameTxt resignFirstResponder]; 
[addressTxt resignFirstResponder]; 
[birthdateTxt resignFirstResponder]; 
[cityTxt resignFirstResponder]; 

return YES; 
    } 


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

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





     - (UITableViewCell *)tableView:(UITableView *)tableView 
     cellForRowAtIndexPath:(NSIndexPath *)indexPath 
     { 
     static NSString *[email protected]"cell"; 

     UITableViewCell *cell=[tableView 
     dequeueReusableCellWithIdentifier:cellIdentifier]; 

     if (cell==nil) 
     { 
    cell=[[UITableViewCell 
    alloc]initWithStyle:UITableViewCellStyleValue1 
     reuseIdentifier:cellIdentifier]; 

    //my added new code 

    label1 = [[UILabel alloc]initWithFrame:CGRectMake(5, 3, 100, 40)]; 
    label1.tag=1; 
    label1.font = [UIFont systemFontOfSize: 20.0]; 
    label1.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | 
    UIViewAutoresizingFlexibleHeight; 
    label1.backgroundColor = [UIColor clearColor]; 
    label1.textColor = [UIColor blackColor]; 
    [cell.contentView addSubview:label1]; 

    label2 = [[UILabel alloc]initWithFrame:CGRectMake(80, 3, 100, 40)]; 
    label2.tag=2; 
    label2.font = [UIFont systemFontOfSize: 20.0]; 
    label2.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | 
     UIViewAutoresizingFlexibleHeight; 
    label2.backgroundColor = [UIColor clearColor]; 
    label2.textColor = [UIColor blackColor]; 
    [cell.contentView addSubview:label2]; 


    label3 = [[UILabel alloc]initWithFrame:CGRectMake(155, 3, 80, 40)]; 
    label3.tag=3; 
    label3.font = [UIFont systemFontOfSize: 20.0]; 
    label3.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | 
    UIViewAutoresizingFlexibleHeight; 
    label3.backgroundColor = [UIColor clearColor]; 
    label3.textColor = [UIColor blackColor]; 
    [cell.contentView addSubview:label3]; 


    label4 = [[UILabel alloc]initWithFrame:CGRectMake(230, 3, 100, 40)]; 
    label4.tag=4; 
    label4.font = [UIFont systemFontOfSize: 20.0]; 
    label4.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | 
    UIViewAutoresizingFlexibleHeight; 
    label4.backgroundColor = [UIColor clearColor]; 
    label4.textColor = [UIColor blackColor]; 
    [cell.contentView addSubview:label4]; 


    label5= [[UILabel alloc]initWithFrame:CGRectMake(320, 3, 120, 40)]; 
    label5.tag=5; 
    label5.font = [UIFont systemFontOfSize: 20.0]; 
    label5.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | 
    UIViewAutoresizingFlexibleHeight; 
    label5.backgroundColor=[UIColor clearColor]; 
    label5.textColor=[UIColor blackColor]; 
    [cell.contentView addSubview:label5]; 

    } 
    else 
    { 
    label1 = (UILabel*)[cell.contentView viewWithTag:1]; 
    label2 = (UILabel*)[cell.contentView viewWithTag:2]; 
    label3 = (UILabel*)[cell.contentView viewWithTag:3]; 
    label4 = (UILabel*)[cell.contentView viewWithTag:4]; 
    label5 = (UILabel*)[cell.contentView viewWithTag:5]; 

    } 


    label1.text=[[data objectAtIndex:indexPath.row]valueForKey:@"fName"]; 
    label2.text=[[data objectAtIndex:indexPath.row]valueForKey:@"lName"]; 
    label3.text=[[data objectAtIndex:indexPath.row]valueForKey:@"adds"]; 
    label4.text=[[data objectAtIndex:indexPath.row]valueForKey:@"birthDay"]; 
    label5.text=[[data objectAtIndex:indexPath.row]valueForKey:@"city"]; 
    /* 
    [cell addSubview:label1]; 
    [cell addSubview:label2]; 
    [cell addSubview:label3]; 
    [cell addSubview:label4]; 
    [cell addSubview:label5]; 
    */ 


    /* [cell.contentView addSubview:label1]; 
    [cell.contentView addSubview:label2]; 
    [cell.contentView addSubview:label3]; 
    [cell.contentView addSubview:label4]; 
    [cell.contentView addSubview:label5]; 
    */ 


     /* cell.textLabel.text=[[data 
    objectAtIndex:indexPath.row]valueForKey:@"fName"]; 
cell.detailTextLabel.text=[[data 
    objectAtIndex:indexPath.row]valueForKey:@"lName"]; 
cell.detailTextLabel.text=[[data 
     objectAtIndex:indexPath.row]valueForKey:@"adds"]; 
cell.detailTextLabel.text=[[data 
    objectAtIndex:indexPath.row]valueForKey:@"birthDay"]; 
cell.detailTextLabel.text=[[data 
    objectAtIndex:indexPath.row]valueForKey:@"city"]; 
*/ 
return cell; 

    } 

    - (void)tableView:(UITableView *)tableView 
    didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
    { 
fnameTxt.text=[[data objectAtIndex:indexPath.row] valueForKey:@"fName"]; 
lnameTxt.text=[[data objectAtIndex:indexPath.row] valueForKey:@"lName"]; 
addressTxt.text=[[data objectAtIndex:indexPath.row] valueForKey:@ 
    "adds"]; 
birthdateTxt.text=[[data objectAtIndex:indexPath.row] valueForKey:@ 
    "birthDay"]; 
cityTxt.text=[[data objectAtIndex:indexPath.row] valueForKey:@"city"]; 

    } 


    - (IBAction)submit:(id)sender 
    { 
     if([fnameTxt.text isEqualToString:@""] || [lnameTxt.text 
    isEqualToString:@""] || [addressTxt.text isEqualToString:@""] || 
    [birthdateTxt.text isEqualToString:@""] || [cityTxt.text isEqualToString:@ 
    ""]) 
     { 
    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"SORRY ERROR 
    !!!" message:@"Please Don't leaves any blanlk detail...." delegate:nil 
    cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; 
    [alert show]; 
     } 
     else 
     { 

    NSString *path=[self getDBPath]; 
    NSLog(@"%@",path); 
    NSString *insertstatement=[NSString stringWithFormat:@"insert into 
    emps (fName,lName,adds,birthDay,city) values 
       ('%@','%@','%@','%@','%@')",fnameTxt.text,lnameTxt.text,addressTxt.text,birthdateTxt.text,cityTxt.text]; 

      NSLog(@"%@",insertstatement); 

    if (sqlite3_open([path UTF8String], &db)==SQLITE_OK) 
    { 
     //  char *errMsg; 
     //  const char *sql_stmt = "CREATE TABLE IF NOT EXISTS imageTbl (id INTEGER PRIMARY KEY AUTOINCREMENT, imagestr TEXT)"; 
     //   
     //  if (sqlite3_exec(db, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK) 
     //  { 
     //   //status.text = @"Failed to create table"; 
     //   NSLog(@"Failed to create table"); 
     //  } 
     //  else 
     //  { 
     //   NSLog(@"create table Successfully"); 
     //  } 
     const char *sql=[insertstatement UTF8String]; 
     char *err; 

     if(sqlite3_exec(db, sql, NULL, NULL, &err)!=SQLITE_OK) 
     { 
      NSLog(@"Error in insert !!!"); 
     } 
     else 
     { 
      NSLog(@"Insert perform successfully!!!"); 
      UIAlertView *alert=[[UIAlertView 
    alloc]initWithTitle:@"Submited..." 
    message:@"Record submited successfully....." delegate:nil 
    cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; 
      [alert show]; 
     } 
     sqlite3_close(db); 
    } 
    else 
    { 
    } 
    [self load]; 
    /* 
    *** code for display the textbox data into alert view *** 
    UIAlertView *aler=[[UIAlertView alloc]initWithTitle:@"user 
    Information" message:[NSString stringWithFormat:@"First Name :%@ \n Last 
    Name :%@ \n Address :%@ \n BirthDate :%@ \n City : %@",fnameTxt.text , 
    lnameTxt.text ,addressTxt.text , birthdateTxt.text , cityTxt.text ] 
    delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil]; 

    [aler show]; 
    */ 
      } 
    } 

    - (IBAction)update:(id)sender 
    { 
     NSString *path=[self getDBPath]; 

     NSString *insertstatement=[NSString stringWithFormat:@"update emps set 
    fName='%@',lName='%@',adds='%@',birthDay='%@',city='%@' where 
    birthDay='%@'" 
    ,fnameTxt.text,lnameTxt.text,addressTxt.text,birthdateTxt.text,cityTxt.text,birthdateTxt.te  xt]; 

     NSLog(@"%@",insertstatement); 

     if (sqlite3_open([path UTF8String], &db)==SQLITE_OK) 
     { 
    const char *sql=[insertstatement UTF8String]; 
    char *err; 

    if(sqlite3_exec(db, sql, NULL, NULL, &err)!=SQLITE_OK) 
    { 
     NSLog(@"Error in Update !!!"); 
    } 
    else 
    { 
     NSLog(@"Update perform successfully!!!"); 
     UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Update..." 
    message:@"Record Updated successfully....." delegate:nil 
     cancelButtonTitle:@"OK" 
     otherButtonTitles:nil, nil]; 
     [alert show]; 
    } 
    sqlite3_close(db); 
     } 
     else 
     { 
     } 
     [self load]; 

    } 

     - (IBAction)deletes:(id)sender 
    { 
     UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"" message:@"Are 
    you sure to DELETE this record ???" delegate:self cancelButtonTitle:@"Cancel" 
    otherButtonTitles:@"OK", nil]; 
[alert show]; 

     /* 
     ***this code written into alert OK button click event *** 

     NSString *path=[self getDBPath]; 

     NSString *insertstatement=[NSString stringWithFormat:@" delete from 
     emp where birthDay='%@' " , birthdateTxt.text]; 

     NSLog(@"%@",insertstatement); 

     if (sqlite3_open([path UTF8String], &db)==SQLITE_OK) 
     { 
     const char *sql=[insertstatement UTF8String]; 
     char *err; 

if(sqlite3_exec(db, sql, NULL, NULL, &err)!=SQLITE_OK) 
{ 
NSLog(@"Error in Delete !!!"); 
} 
else 
{ 
NSLog(@"Delete perform successfully!!!"); 
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Delete..." 
    message:@"Record Deleted successfully....." delegate:nil 
    cancelButtonTitle:@"OK" 
    otherButtonTitles:nil, nil]; 
[alert show]; 
} 
sqlite3_close(db); 
} 
else 
{ 
} 
[self load]; 

*/ 
    } 


    // *** code for alertview button click *** 

    - (void)alertView:(UIAlertView *)alertView 
    clickedButtonAtIndex:(NSInteger)buttonIndex 
    { 
if (buttonIndex == 0) 
{ 

} 
if (buttonIndex == 1) 
{ 
    NSString *path=[self getDBPath]; 

    NSString *insertstatement=[NSString stringWithFormat:@" delete from 
    emps where birthDay='%@' " , birthdateTxt.text]; 

    NSLog(@"%@",insertstatement); 

    if (sqlite3_open([path UTF8String], &db)==SQLITE_OK) 
    { 
     const char *sql=[insertstatement UTF8String]; 
     char *err; 

     if(sqlite3_exec(db, sql, NULL, NULL, &err)!=SQLITE_OK) 
     { 
      NSLog(@"Error in Delete !!!"); 
     } 
     else 
     { 
      NSLog(@"Delete perform successfully!!!"); 
      UIAlertView *alert=[[UIAlertView 
    alloc]initWithTitle:@"Delete..." 
    message:@"Record Deleted successfully....." delegate:nil 
    cancelButtonTitle:@"OK" 
    otherButtonTitles:nil, nil]; 
      [alert show]; 
     } 
     sqlite3_close(db); 
    } 
    else 
    { 
    } 
    [self load]; 

     } 

    } 


    -(NSString *)getDBPath 
    { 
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
    NSUserDomainMask, YES); 
NSString *documentdirectory=[paths objectAtIndex:0]; 
NSString *inspath=[NSString stringWithFormat:@"sample.sqlite"]; 
NSString *destpath=[documentdirectory 
    stringByAppendingPathComponent:inspath]; 

return destpath; 
    } 

    - (void)didReceiveMemoryWarning 
    { 
[super didReceiveMemoryWarning]; 
// Dispose of any resources that can be recreated. 
    } 
    @end 

내 위의 코드를 참조하십시오, 그냥 사용자 정의 셀에 대해 말해 ...

답변

2

cellForRowAtIndexPath 테이블 뷰 방법 내부. 이 코드를 사용자 정의 uitableviewcell 클래스로 바꿔야합니다. 그리고 나서이 내부에서 nib 파일을 만들고 cellForRowAtIndexPath 메서드 안에로드해야합니다.

//이 코드

// UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 

// 아래에 언급 된 링크 코드와 같은 위의 코드를 수정에게 코멘트.

당신이 말하는 CustomUiTableViewCell

+0

제발 나를 투표하십시오. – MAC113

0

참조하십시오 "... UILabel의 대신에 사용자 정의 셀은 내가 무엇을 할 수 있습니까?"

당신이 무엇을 요구하고 있는지 분명하지 않습니다. 테이블 뷰 셀은 테이블 뷰 내에 만 존재하며 테이블 뷰는 테이블 뷰 셀 대신 UILabel을 포함 할 수 없습니다. 그들은 서로 교환 할 수 없다.

많은 코드를 게시했습니다. 대부분 보일러 플레이트 코드가 표준입니다. 나는 그 모든 것을 성가 시게했다. (성가 셨다 ...)

cellForRowAtIndexPath 메서드에서 표준 UITableViewCell을 만들고 5 개의 UILabels를 추가하고있다. 라벨이 너무 커서 셀에 맞지 않는 것처럼 보입니다.하지만 그건 보조입니다.

IBOutlets로 레이블이 포함 된 UITableViewCell의 사용자 지정 하위 클래스를 만들고 표준 셀보다는 사용자 지정 셀을 인스턴스화하려고합니까?

무엇을 하려는지 명확하게 진술하십시오.

스토리 보드 또는 XIB 파일을 사용하고 있고 UITableViewController 또는 표준보기 컨트롤러를 사용 중인지 알려줄 필요가 있습니다.

관련 문제