2013-03-06 2 views
1

Я новичок в разработке iPhone. У меня есть один UITableView с тремя разделами, и каждый раздел имеет три строки. И у меня есть один UISegmentedControl с тремя index.the tableview скрыт изначально. Когда я выбираю любой индекс segmentIndex, тогда его отображение tableview с тремя разделами. Но мой вопрос заключается в том, что когда я выбираю индекс сегментированного контроля затем его отображения, в котором Tableview только с одной секцией и два других раздела является скрытие в tableView.How, чтобы сделать это, пожалуйста, ответьте
Вот мой кодUITableView и UISegmentedControl

#import "DetailViewController.h" 


@interface DetailViewController() 

@end 

@implementation DetailViewController 

@synthesize tblView; 

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{ 
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
    if (self) { 
    // Custom initialization 
    } 
    return self; 
} 


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

    //Customize tableview 
    tblView = [[UITableView alloc] init]; 
    firstName = [NSArray arrayWithObjects:@"Parth",@"Bhadresh",@"Marshal", nil]; 
    middleName = [NSArray  arrayWithObjects:@"Dipakbhai",@"Dineshbhai",@"Mansukhbhai",nil]; 
    lastName = [NSArray arrayWithObjects:@"Patel",@"Laiya",@"Kaneria", nil]; 
    tblView.delegate = self; 
    tblView.dataSource = self; 
} 

-(void)viewWillAppear:(BOOL)animated 
{ 
    sgmtControl.frame = CGRectMake(17, 180, 285, 44);  
    tblView.frame = CGRectMake(0, 0, 320, 364); 
    tblView.hidden = YES; 
    [self.view addSubview:tblView]; 
} 
- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return 3; 
} 

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    switch (section) 
    { 
     case 0: 
      return 3; 
      break; 
     case 1: 
      return 3; 
      break; 
     case 2: 
      return 3; 
      break; 
    } 
    return 0; 
} 

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection: (NSInteger)section 
{ 
    switch (section) 
    { 
     case 0: 
      return @"FirstName"; 
      break; 
     case 1: 
      return @"MiddleName"; 
      break; 
     case 2: 
      return @"LastName"; 
      break; 
    } 
    return nil; 
} 

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

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

    switch (indexPath.section) 
    { 
     case 0: 
      cell.textLabel.text =[firstName objectAtIndex:indexPath.row]; 
      break; 
     case 1: 
      cell.textLabel.text = [middleName objectAtIndex:indexPath.row]; 
      break; 
     case 2: 
      cell.textLabel.text = [lastName objectAtIndex:indexPath.row]; 
      break; 
    } 
    return cell; 
} 
-(IBAction)changeSegement:(id)sender 
{ 
    if(sgmtControl.selectedSegmentIndex == 0) 
    { 
     tblView.hidden = NO; 
    } 
    else if (sgmtControl.selectedSegmentIndex == 1) 
    { 
     tblView.hidden = NO; 
    } 
    else if (sgmtControl.selectedSegmentIndex == 2) 
    { 
     tblView.hidden = NO; 
    } 
} 
+0

перезагрузить таблицу в каждом сегменте нажмите – Rushabh

+0

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

ответ

3

Делай так,

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

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 

    switch (sgmtControl.selectedSegmentIndex) 
    { 
     case 0: 
      return [firstName count]; 
      break; 
     case 1: 
      return [middleName count]; 
      break; 
     case 2: 
      return [lastName count]; 
      break; 
    } 
    return 0; 
} 

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection: (NSInteger)section 
{ 
    switch (sgmtControl.selectedSegmentIndex) 
    { 
     case 0: 
      return @"FirstName"; 
      break; 
     case 1: 
      return @"MiddleName"; 
      break; 
     case 2: 
      return @"LastName"; 
      break; 
    } 
} 

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

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

    switch (sgmtControl.selectedSegmentIndex) 
    { 
     case 0: 
      cell.textLabel.text =[firstName objectAtIndex:indexPath.row]; 
      break; 
     case 1: 
      cell.textLabel.text = [middleName objectAtIndex:indexPath.row]; 
      break; 
     case 2: 
      cell.textLabel.text = [lastName objectAtIndex:indexPath.row]; 
      break; 
    } 
    return cell; 
} 
-(IBAction)changeSegement:(id)sender 
{ 
    if(sgmtControl.selectedSegmentIndex == 0) 
    { 
     tblView.hidden = NO; 
    } 
    else if (sgmtControl.selectedSegmentIndex == 1) 
    { 
     tblView.hidden = NO; 
    } 
    else if (sgmtControl.selectedSegmentIndex == 2) 
    { 
     tblView.hidden = NO; 
    } 
    [tblView reloadData]; 
} 
+0

спасибо. он работает отлично, как мне нужно. –

+0

@parthpatel, если вы в порядке с этим, принимайте ответ .... – Venkat

0

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

Вам нужно, чтобы ваш cellForRowAtIndexPath проверил, какой сегмент выбран, и верните правильный набор ячеек.

Когда пользователь меняет сегментированную кнопку, имейте changeSegment: сохраните выбранный сегмент в переменной экземпляра. Затем позвоните ему [self reloadData];

#import "DetailViewController.h" 


@interface DetailViewController() 
{ 
    NSArray *names; 
    NSInteger segIndex; 
} 
@property (nonatomic, strong) NSArray *names; 
@property (nonatomic) segIndex; 
@end 

@implementation DetailViewController 

@synthesize tblView; 
@synthesize names; 
@synthesize segIndex; 

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{ 
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
    if (self) { 
     // Custom initialization 
    } 
    return self; 
} 


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

    //Customize tableview 
    tblView = [[UITableView alloc] init]; 
    self.names = [NSArray arrayWithObjects: [NSArray arrayWithObjects:@"Parth",@"Bhadresh",@"Marshal", nil], 
              [NSArray arrayWithObjects:@"Dipakbhai",@"Dineshbhai",@"Mansukhbhai",nil], 
              [NSArray arrayWithObjects:@"Patel",@"Laiya",@"Kaneria", nil], 
        nil]; 
    tblView.delegate = self; 
    tblView.dataSource = self; 
} 

-(void)viewWillAppear:(BOOL)animated 
{ 
    sgmtControl.frame = CGRectMake(17, 180, 285, 44); 
    tblView.frame = CGRectMake(0, 0, 320, 364); 
    tblView.hidden = YES; 
    [self.view addSubview:tblView]; 
} 
- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return [self.names count]; 
} 

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return [[self.names objectAtIndex:section] count]; 
} 

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection: (NSInteger)section 
{ 
    switch (section) 
    { 
     case 0: 
      return @"FirstName"; 
     case 1: 
      return @"MiddleName"; 
     case 2: 
      return @"LastName"; 
    } 
    return nil; 
} 

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

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

    cell.textLabel.text =[[self.names objectAtIndex:self.segIndex] objectAtIndex:indexPath.row]; 

    return cell; 
} 
-(IBAction)changeSegement:(id)sender 
{ 
    self.segIndex = sgmtControl.selectedSegmentIndex; 
    [self reloadData]; 
} 
+0

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

+0

Спасибо, что это тоже работает решетка. –

+0

@parthpatel Добро пожаловать. Если это код, который вы использовали в своей программе, отметьте этот ответ как ответ на свой вопрос. –

0

Попробуйте

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

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
switch (sgmtControl.selectedSegmentIndex) 
{ 
    case 0: 
     return 3; 
     break; 
    case 1: 
     return 3; 
     break; 
    case 2: 
     return 3; 
     break; 
} 
return 0; 
} 

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection: (NSInteger)section 
{ 
switch (sgmtControl.selectedSegmentIndex) 
{ 
    case 0: 
     return @"FirstName"; 
     break; 
    case 1: 
     return @"MiddleName"; 
     break; 
    case 2: 
     return @"LastName"; 
     break; 
    } 
} 

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

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

switch (sgmtControl.selectedSegmentIndex) 
{ 
    case 0: 
     cell.textLabel.text =[firstName objectAtIndex:indexPath.row]; 
     break; 
    case 1: 
     cell.textLabel.text = [middleName objectAtIndex:indexPath.row]; 
     break; 
    case 2: 
     cell.textLabel.text = [lastName objectAtIndex:indexPath.row]; 
     break; 
} 
return cell; 
    } 
+0

спасибо, его решетка –

1

Немного изменения в коде Mountain Lion, чтобы сделать его более универсальным и удалить переключатели

@synthesize currentArray; 
. 
. 
. 
. 

- (void)viewDidLoad 
{ 
     . 
     . 
     . 
     //ALLOCATE currentArray 
} 
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return 1; 
} 

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return currentArray.count; 
} 

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection: (NSInteger)section 
{ 
    switch (sgmtControl.selectedSegmentIndex) 
    { 
     case 0: 
      return @"FirstName"; 
      break; 
     case 1: 
      return @"MiddleName"; 
      break; 
     case 2: 
      return @"LastName"; 
      break; 
    } 
} 

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

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

    cell.textLabel.text =[currentArray objectAtIndex:indexPath.row]; 
    return cell; 
} 
-(IBAction)changeSegement:(id)sender 
{ 
    if(sgmtControl.selectedSegmentIndex == 0) 
    { 
     currentArray = firstName; 
    } 
    else if (sgmtControl.selectedSegmentIndex == 1) 
    { 
     currentArray = middleName; 
    } 
    else if (sgmtControl.selectedSegmentIndex == 2) 
    { 
     currentArray = lastName; 
    } 
    tblView.hidden = NO; 
    [tblView reloadData]; 
} 
0
//You may get hint from my code 
    //UISegmentedControl with TableView using Objective C 

    //complete working code 

@interface TabTwoScheduleViewController() <UITableViewDelegate ,  UITableViewDataSource> 
{ 
CGRect rect; 
NSArray *list; 
NSArray *list1; 
NSArray *list2; 
NSArray *list3; 
NSArray *list4; 
UITableView *segmentTableView; 
} 
@end 

@implementation TabTwoScheduleViewController 

- (void)viewDidLoad { 
[super viewDidLoad]; 

rect = [[UIScreen mainScreen]bounds]; 

UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(10, 10, rect.size.width-20, rect.size.height/10-23)]; 
scroll.contentSize = CGSizeMake(rect.size.width, rect.size.height * 2); 
scroll.showsHorizontalScrollIndicator = YES; 
scroll.backgroundColor = [UIColor yellowColor]; 

NSArray *itemArray = [NSArray arrayWithObjects: @"ONLINE", @"CLASSROOM", @"WEBCASTING", nil]; 
list = [NSArray  arrayWithObjects:@"list.1",@"list.2",@"list.3",@"list.4",@"list.5", nil]; 
list1 = [NSArray arrayWithObjects:@"list1.1",@"list1.2",@"list1.3",@"list1.4",@"list1.5", nil]; 
list2 = [NSArray arrayWithObjects:@"list2.1",@"list2.2",@"list2.3",@"list2.4",@"list2.5", nil]; 
list3 = [NSArray arrayWithObjects:@"list3.1",@"list3.2",@"list3.3",@"list3.4",@"list3.5", nil]; 
list4 = [NSArray arrayWithObjects:@"list4.1",@"list4.2",@"list4.3",@"list4.4",@"list4.5", nil]; 

// segmentedControl is declared as property 
self.segmentedControl = [[UISegmentedControl alloc]  initWithItems:itemArray]; 
self.segmentedControl.frame = CGRectMake(0, 0, rect.size.width-20, 50); 
self.segmentedControl.segmentedControlStyle =UISegmentedControlStylePlain; 
[self.segmentedControl addTarget:self action:@selector(MySegmentControlAction:) forControlEvents:  UIControlEventValueChanged]; 
self.segmentedControl.selectedSegmentIndex = 0; 
[scroll addSubview:self.segmentedControl]; 
[self.view addSubview:scroll]; 

//ADDING TABLEVIEW OVER VIEW(I added this view to get leading and trailing space for tableViewCell) 

UIView *vw = [[UIView alloc]initWithFrame:CGRectMake(0, 70, rect.size.width, rect.size.height)]; 
    vw.backgroundColor = [UIColor redColor]; 
[self.view addSubview:vw]; 

    //TABLE VIEW 
segmentTableView = [[UITableView alloc]initWithFrame:CGRectMake(10, 0, rect.size.width-20, rect.size.height-230) style:UITableViewStylePlain]; 
segmentTableView.backgroundColor = [UIColor yellowColor]; 

segmentTableView.delegate = self; 
segmentTableView.dataSource = self; 

[vw addSubview:segmentTableView]; 
    } 

// number of sections for tableView 
- (NSInteger)numberOfSectionsInTableView:(UITableView *)theTableView 
{ 
NSInteger a=0; 
switch (self.segmentedControl.selectedSegmentIndex) 
{ 
    case 0: 
     a=list.count; 
    break; 

case 1: 
    a=list1.count; 
    break; 

case 2: 
    a=list1.count; 
    break; 

    default: 
    a=list1.count; 
    break; 
} 
    return a; 
} 
// number of row in the section 
- (NSInteger)tableView:(UITableView *)theTableView numberOfRowsInSection:(NSInteger)section 
{ 
return 1; 
} 
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
static NSString *simpleTableIdentifier = @"ScheduleCustomTableViewCell"; 

//ScheduleCustomTableViewCell is name of custom TabelViewCell 
ScheduleCustomTableViewCell *cell =(ScheduleCustomTableViewCell *) [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier]; 
if (cell == nil) 
{ 
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ScheduleCustomTableViewCell" owner:self options:nil]; 
cell = [nib objectAtIndex:0]; 
} 

// conditions to get different values on label 
if (self.segmentedControl.selectedSegmentIndex==0) 
{ 
cell.labelAddress1.text = [list objectAtIndex:indexPath.section]; 
cell.labelAddress2.text = [list1 objectAtIndex:indexPath.section]; 
} 
else if (self.segmentedControl.selectedSegmentIndex==1) 
{ 
cell.labelAddress1.text = [list1 objectAtIndex:indexPath.section]; 
cell.labelAddress2.text = [list2 objectAtIndex:indexPath.section]; 
} 
else 
{ 
cell.labelAddress1.text = [list2 objectAtIndex:indexPath.section]; 
cell.labelAddress2.text = [list3 objectAtIndex:indexPath.section]; 
} 
cell.backgroundColor = [UIColor yellowColor]; 

return cell ; 
} 
-(CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath 
{ 
return 130; 
} 
// Header is given to get spacing between TableViewCells 
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section 
{ 
return 10; 
} 

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section 
{ 
UIView *headerView = [[UIView alloc] init]; 
headerView.backgroundColor = [UIColor redColor]; 
return headerView; 
} 

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

}

- (void)MySegmentControlAction:(UISegmentedControl *)segment 
{ 
[segmentTableView reloadData]; 
} 

@end 
Смежные вопросы