2012-01-04 3 views
2

Storyboards와 Objective-C 코딩의 차이를 이해하기 위해 애써 왔습니다. 스토리 보드에 객체를 드래그하거나 Objective-C 내에서 새로운 뷰로 코딩함으로써 UITableView를 생성 할 수 있습니다.프로그래밍 방식으로 UITableView를 만들고 Xcode 4.2에서 NSArray를 채우는 방법?

문제는 가능한 한 슬림형으로 스토리 보드를 유지하고 싶다는 것입니다. 그래서 빌드하고 UITableView 5 문자열 NSArray 함께 채우는 중이 야. 내 코드는 컴파일러 오류를 반환하기 전에 1 행을 실행합니다 ... 나는 전체 프로젝트를 스크랩하고 신선한 시작거야.

새 Xcode 4.2/iOS5/Storyboards에 익숙한 누군가가 UITableView를 작성하기위한 합리적인 솔루션을 제공 할 수 있다면 매우 감사하게 생각합니다. 나는 이것이 시작하기에 너무 초조 한 이유 인 기본적인 작업임을 안다. 테이블 뷰를 사용할 수는 있지만 Array를 동적으로 채우고 #X 행을 만들 수없는 것 같습니다 ...

더 많은 정보를 제공 할 수 있는지 알려주세요. 단지 작업의 TableView를 얻을 수 및 배열 :

편집로 채울 필요 - - 가능한 한 I는 간단하려고했습니다 여기 내 project source code 당신은 내가 어디에 있어요 체크 아웃 다운로드 할 수 있습니다.

+0

tableview 클래스의 샘플 코드가 있습니까? UITableViewController의 하위 클래스로 만드는 것이 훨씬 쉽습니다. Pls에는 헤더와 구현 파일이 모두 포함됩니다. – chourobin

+0

@chourobin 확실한 것은 내 원래의 게시물에 내 xcode 프로젝트 소스를 첨부했습니다. – Jake

+0

@ JakeRocheleau - 궁금 해서요, 왜 당신의 스토리 보드를 가능한 한 슬림 좋게 만들고 싶습니까? 인터페이스 빌더와 같은 스토리 보딩 (Storyboarding)은 그래픽 작업을 통해 가벼운 코드를 사용하고 API 변경으로 인한 향후 오류를 예방할 수 있다는 인상하에있었습니다. – 5StringRyan

답변

3

는 스토리 보드에 대신 정적 세포의 동적 프로토 타입에있는 tableview를 변경해야한다는 것입니다 충돌 이유. 어떤 이유로 정적 셀이 기본 설정입니다. Storyboards를 사용하면 테이블 뷰를 처리 할 때 특히 유용합니다. 초기 뷰는 MasterviewController가 RootViewController 인 NavigationController로 설정되어 있으므로 firstView로로드됩니다. MainStoryboard에서 TableView를 클릭하고 Cels를 Dynamic Prototypes로 변경하십시오. 그렇지 않으면 스토리 보드에서 직접 만든 고정 점을 사용할 것입니다. 스토리 보드의 테이블 뷰에서 맞춤형 셀을 바로 만들 수 있습니다. 주목해야 할 또 하나의 사실은 재사용 식별자가 스토리 보드와 TableViewController에서 같은 이름으로 설정되어야한다는 것입니다. 정적 셀 수를 항상 같을 것이라는 것을 알고 있으면 원하는 수만큼 정적 셀 수를 늘릴 수도 있습니다.

+1

어떤 이유로 정적 셀이 기본 설정입니다. Storyboards를 사용하면 테이블 뷰를 처리 할 때 특히 유용합니다. –

+0

남자 정말 고마워요! 이 문제는 솔직히 오랫동안 나를 실망 시켰습니다. 나는 단지 몇 주 동안 그것을 파악할 수 없었고 이제는 마침내 내 프로젝트로 전진 할 수있게되었습니다. '재사용 식별자'에 대한 설명과 스토리 보드에서이 값을 어디에 설정해야합니까? – Jake

+0

기본값이 정적 인 이유가 나를 넘어 있습니다. 대부분의 테이블 뷰는 Dynamic Prototypes입니다. –

3

다음은 샘플 코드에서 NSArray (NSMutableArray)로 채워진 UITableViewController를 서브 클래 싱하는 간단한 샘플입니다. 스토리 보드는 사용하지 않지만 귀하의 의견에는 괜찮습니다. 다행히도 샘플 코드가 도움이되기를 바랍니다.

헤더 :

@interface MainTableViewController : UITableViewController 
{ 
    NSMutableArray *_items; 
} 

@end 

구현 :

@implementation MainTableViewController 

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 
#pragma mark - 
#pragma mark Lifetime 
#pragma mark - 
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 

- (id)initWithStyle:(UITableViewStyle)style 
{ 
    self = [super initWithStyle:style]; 
    if (self) 
    { 
     // datastore 
     _items = [[NSMutableArray alloc] init]; 
     for (int index=0; index < 5; index++) 
     { 
      [_items addObject:[NSString stringWithFormat:@"item #%d", index]];    
     } 
    } 
    return self; 
} 

- (void)dealloc 
{ 
    [_items release]; 
    [super dealloc]; 
} 

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 
#pragma mark - 
#pragma mark Table View DataSource 
#pragma mark - 
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    // a typical table has one section 
    return 1; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    // number of rows 
    return [_items count]; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    // NSIndexPath contains an array of indexes. For UITableView: 
    // indexAtPosition:0 is the section number 
    // indexAtPosition:1 is the row number 

    // create an identifier for this type of cell 
    static NSString *CellIdentifier = @"Cell"; 

    // get a cell of this type from the re-use queue or create one 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) 
    { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
    } 

    // Configure the cell... 
    NSString *title = [_items objectAtIndex:[indexPath indexAtPosition:1]]; 
    [[cell textLabel] setText:title]; 
    [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator]; 

    return cell; 
} 


// Override to support conditional editing of the table view. 
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    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 
     NSLog(@"delete section: %d rol: %d", [indexPath indexAtPosition:0], [indexPath indexAtPosition:1]); 
     [_items removeObjectAtIndex:[indexPath indexAtPosition:1]]; 
     [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 
     NSLog(@"insert section: %d rol: %d", [indexPath indexAtPosition:0], [indexPath indexAtPosition:1]);   
    } 
} 

// Override to support rearranging the table view. 
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath 
{ 
    NSString *fromItem = [_items objectAtIndex:[fromIndexPath indexAtPosition:1]]; 
    [_items removeObjectAtIndex:[fromIndexPath indexAtPosition:1]]; 
    [_items insertObject:fromItem atIndex:[toIndexPath indexAtPosition:1]]; 
} 

// Override to support conditional rearranging of the table view. 
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    return YES; 
} 

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    return 
} 
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 
#pragma mark - 
#pragma mark UITableViewDelegate 
#pragma mark - 
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    NSLog(@"selected section: %d rol: %d", [indexPath indexAtPosition:0], [indexPath indexAtPosition:1]); 

    // get the selected cell 
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 
    [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator]; 

    // navigate to detail 
    DetailedTableViewController *detailedView = [[DetailedTableViewController alloc] init]; 
    [[self navigationController] pushViewController:detailedView animated:YES]; 
} 

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 
#pragma mark - 
#pragma mark View lifecycle 
#pragma mark - 
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 

- (void)didReceiveMemoryWarning 
{ 
    // Releases the view if it doesn't have a superview. 
    [super didReceiveMemoryWarning]; 
} 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    // 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] setRightBarButtonItem: [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 (interfaceOrientation == UIInterfaceOrientationPortrait); 
} 

@end 
관련 문제