2014-12-22 2 views
2

Я делаю модуль входящей почты в своем приложении. Сначала загружается 20 сообщений с сервера. Я хочу, чтобы после 20 сообщений в ячейке UItableview создавалась метка с именем «загрузить больше сообщений». и после нажатия на эту метку я хочу сделать еще один звонок на сервер. Я пробовал следующий код, но он не работает. спасибо заранее :( It is showing like this i want to show it after recprds has been laoded ниже мой пример кода cellForRowAtIndexPath и numberOfRowsInSectionсоздать действие метки пользовательского интерфейса в tableviewcell

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

    return [inboxmessagesarray count]+1; 
} 

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 

    static NSString *tableviewidentifier = @"cell"; 
    __block tablecellTableViewCell *cell= [self.activitiesTableView_ dequeueReusableCellWithIdentifier:tableviewidentifier]; 

    if(cell==nil) 
    { 
     cell = [[tablecellTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:tableviewidentifier]; 
    }if(indexPath.row == [self tableView:self.activitiesTableView_ numberOfRowsInSection:indexPath.section] - 1){ 
     [email protected]"Load More Record";// here i am making a label but it is not showing at the end of tableview cell 



    } 
    else{ 

    __block NSString *row = [NSString stringWithFormat:@"%ld",(long)indexPath.row]; 

    cell.titlename.font=[UIFont fontWithName:@"SegoeUI" size:15]; 
    cell.tolbl.font=[UIFont fontWithName:@"SegoeUI-light" size:12]; 
    cell.fromlbl.font=[UIFont fontWithName:@"SegoeUI-light" size:12]; 
    cell.datelbl.font=[UIFont fontWithName:@"SegoeUI-light" size:8]; 
    cell.timelbl.font=[UIFont fontWithName:@"SegoeUI-light" size:8]; 
     if([[[self.inboxmessagesarray objectAtIndex:indexPath.row]objectForKey:@"messageRead"] intValue]==0) 
    { 

     cell.titlename.font=[UIFont fontWithName:@"SegoeUI" size:15]; 
     cell.tolbl.font=[UIFont fontWithName:@"SegoeUI-light" size:12]; 
     cell.fromlbl.font=[UIFont fontWithName:@"SegoeUI-light" size:12]; 
     cell.datelbl.font=[UIFont fontWithName:@"SegoeUI-light" size:8]; 
     cell.timelbl.font=[UIFont fontWithName:@"SegoeUI-light" size:8]; 

       cell.contentView.backgroundColor=[UIColor lightGrayColor]; 



    } 
    else 
    { 
     cell.titlename.font=[UIFont fontWithName:@"SegoeUI" size:15]; 
     cell.tolbl.font=[UIFont fontWithName:@"SegoeUI-light" size:12]; 
     cell.fromlbl.font=[UIFont fontWithName:@"SegoeUI-light" size:12]; 
     cell.datelbl.font=[UIFont fontWithName:@"SegoeUI-light" size:8]; 
     cell.timelbl.font=[UIFont fontWithName:@"SegoeUI-light" size:8]; 

     cell.contentView.backgroundColor=[UIColor clearColor]; 

    } 
    cell.titlename.text=[[self.inboxmessagesarray objectAtIndex:indexPath.row]objectForKey:@"offerTitle"]; 
    //toCity 

    cell.tolbl.text=[[self.inboxmessagesarray objectAtIndex:indexPath.row]objectForKey:@"toCity"]; 
    cell.fromlbl.text=[[self.inboxmessagesarray objectAtIndex:indexPath.row]objectForKey:@"fromCity"]; 
    if(![[imagesDictionary allKeys] containsObject:row]) //if image not found download and add it to dictionary 
    { 
     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{ 
      NSString *img=[[self.inboxmessagesarray objectAtIndex:indexPath.row]objectForKey:@"offerPhoto"];// here i am getting image path 
      NSURL *url = [NSURL URLWithString:img]; 
      NSData * imageData = [NSData dataWithContentsOfURL:url]; 
      UIImage *image = [UIImage imageWithData:imageData]; 

      dispatch_sync(dispatch_get_main_queue(), ^{ //in main thread update the image 
       [imagesDictionary setObject:image forKey:row]; 
       cell.profileimage.image = image; 
       cell.textLabel.text = @""; //add this update will reflect the changes 
       NSLog(@"loading and adding to dictionary"); 
      }); 
     }); 
    } 
    else 
    { 
     cell.profileimage.image = [imagesDictionary objectForKey:row]; 
     NSLog(@"retriving from dictionary"); 
    } 


    cell.datelbl.text=[[self.inboxmessagesarray objectAtIndex:indexPath.row]objectForKey:@"messageDate"]; 
    cell.timelbl.text=[[self.inboxmessagesarray objectAtIndex:indexPath.row]objectForKey:@"messageTime"]; 
    } 

return cell; 
} 
+0

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

+0

ярлык не отображается правильно ...u может прочитать мой полный вопрос ' –

+0

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

ответ

0

вы можете использовать это в нескольких типах здесь я добавляю в 3-х типов, настроить ваш сам

выбор Нет 1

считать, что и получить все данные (например, 100) с сервера, хранить в какой-то NSMutableArray, концепция объявить один глобальный int

int loadMoreItems; 

в вашем viewWillAppear

-(void)viewWillAppear:(BOOL)animated 
{ 
    loadMoreItems=21; // initially set the count is more than 20 
} 

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
if ([yourTotalArrayName count]<=loadMoreItems) { 
     return [yourTotalArrayName count]; 
    } 
    else { 
     return loadMoreItems; 
    } 

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

// add your data 

if (indexPath.row+1<loadMoreItems) 
      { 

     cell.lblLoadMoreItems.hidden=YES; 
    cell.itemsdetails.text = [NSString stringWithFormat:@"%@",[yourTotalArrayName objectAtIndex:indexPath.row]] ; 
    } 
else 

    { 
     cell.itemsdetails.hidden=YES; 
     cell.lblLoadMoreItems.text = @"Load more results...!"; 

    } 
} 


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

    if (indexPath.row+1<loadMoreItems) { 
    // here do your stuff here 


    } 
    else { 
     loadMoreItems=loadMoreItems+20; 
     [self.yourtableview reloadData]; 
    } 

выбора нет 2

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
// Classic start method 

// here add your data loaded 

if (indexPath.row == [self.yourarrayName count] - 1) 
{ 
    cell.lblLoadMoreItems.text = @"Load more results...!"; 
    [self launchReload]; 
} 
} 



    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

    if (indexPath.row == [self.yourarrayName count] - 1) 
{ 

    [self launchReload]; 
} 

} 



    -(void)launchRelaod 

{ 
// call the webservice 

    [self.yourtableview reloadData]; 
} 

choiceNo 3

use 2 prototype cell in `UItableView` 

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

    return [yourarrayname count] + 1; 
    } 


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

static NSString *postCellId = @"postCell"; 
static NSString *moreCellId = @"moreCell"; 
    UITableViewCell *cell = nil; 



if ([indexPath row] == [yourarrayname count]) { 

    cell = [tableView dequeueReusableCellWithIdentifier:moreCellId]; 

    if (cell == nil) { 
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:moreCellId]; 
    } 

    cell.textLabel.text = @"Load more items..."; 
    cell.textLabel.textColor = [UIColor blueColor]; 


} 
else 
{ 
    cell = [tableView dequeueReusableCellWithIdentifier:postCellId]; 
    if (cell == nil) { 
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:postCellId]; 
    } 

    // show your Data 
} 

return cell; 
} 



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

    if ([indexPath row] == [yourarrayname count]) { 

    // call the web service and reload Data of UItableview 
    } 
else 

    { 
    //normall selcftion procedure 
} 

} 
+0

wait Я загружаю вариант 2 –

+0

ok Я жду –

+0

действительно помог :) –

0

Добавить ярлык в footerview за столом в.

tableview.tableFooterView = label; 

К этому вы получите этикетку в конце ваш стол всегда.

И для нагрузки более действий добавить крана жесты на этикетке.

+0

@ Мишал Аван в действии вы снова обращаетесь к серверу или у вас есть все данные в вашем inboxmessagesarray? – Hiren

+0

Да, мне нужно перезагрузить данные на нем –

1

пытаются использовать следующие Methods из UITableView

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section { 
    return 40; 
} 

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section { 

    UIView * viewHeader = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 40)]; 
    [viewHeader setBackgroundColor:[UIColor redColor]]; 

    UIButton * btnLoadMore = [UIButton buttonWithType:UIButtonTypeCustom]; 
    [btnLoadMore setFrame:CGRectMake(10, 5, 300, 30)]; 
    [btnLoadMore setTitle:@"Load More Record" forState:UIControlStateNormal]; 
    [btnLoadMore setTintColor:[UIColor blackColor]]; 
    [btnLoadMore setBackgroundColor:[UIColor clearColor]]; 
    [btnLoadMore addTarget:self action:@selector(loadMoreRecords:) forControlEvents:UIControlEventTouchUpInside]; 
    [viewHeader addSubview:btnLoadMore]; 
    return viewHeader; 
} 

- (void)loadMoreRecords : (id) sender { 
    NSLog(@"Your code to load more data"); 
} 
+0

Я добавил этот код, но я не видел ни одного нижнего колонтитула –

0

Если вы просто хотите что-то, чтобы показать, на дне или ниже Tableview вы просто осуществить быстрый шаг:

Это будет отменять любые беды Автокомпоновки или неприятности с рамкой UILabels или происхождение (он никогда не будет двигаться)

UIView* footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.bounds.size.width, 25)]; 
UIButton *loadMoreButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 25)]; 
[loadMoreButton setTitle:@"Load More" forState:UIControlStateNormal]; 
[loadMoreButton addTarget:self action:@selector(loadMore:) forControlEvents:UIControlEventTouchUpInside]; 
//More customizing 
[footerView addSubview:loadMoreButton]; 
self.tableView.tableFooterView = footerView; 

-(IBAction)loadMoreButton:(id)sender { 
//load more from server 
} 
+0

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

+0

@MishalAwan Вы можете поместить его в функцию void и вызвать его, когда все сообщения загружены так, как вы хотите. Это легкая часть. Я не знаю, как вы настроили свой TableView, но просто добавьте его туда, где вы создаете свои ячейки, и как только все они созданы и загружены, тогда отобразите footerView – soulshined

1

Как и хотите ряд, чтобы быть добавлены к Tableview, который показывает Load More Records и может это сделать 2 способами либо путем добавления вид колонтитула или каждый ла й ряд, переходя один дополнительный ряд в методе -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section и возвращать определенную ячейку для этой строки в -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

, например, добавить еще один пользовательскую ячейку в Tableview и добавить метку и установить ее текст Load more record и установить его повторное использование идентификатор, как LabelCell

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return self.inboxmessagesarray.count + 1 ; 
} 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    //[self performSegueWithIdentifier:@"segueIdentifier" sender:tableView]; 
    if(indexPath.row == [self.inboxmessagesarray count]) 
    { 
     NSLog(@"load more records"); 
    } 
} 

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    __block tablecellTableViewCell *cell= [tableView dequeueReusableCellWithIdentifier:tableviewidentifier]; 
    if(cell == nil) 
    { 
     cell = [[tablecellTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tableviewidentifier]; 
    } 
    //in the last row 
    if(indexPath.row == self.inboxmessagesarray.count) 
    { 
     cell = [tableView dequeueReusableCellWithIdentifier:@"LabelCell"]; 
     if(cell == nil) 
     { 
      cell = [[tablecellTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"LabelCell"]; 
     } 
     if([self.inboxmessagesarray count] > 0) 
      cell.hidden = NO; 
     else 
      cell.hidden = YES; 

     return cell; 
    } 
    //..rest of the code 
Смежные вопросы