2014-10-06 3 views
0

В настоящее время у меня есть UITableView в моем MatchCenterViewController, и я сконструировал его для загрузки 10 строк для каждого раздела, но показываю только первые 4, сделав heightForRowAtIndexPath верным значением 0 для остальных. То, что я хочу сделать, - это кнопка в нижней части каждого раздела, которая при нажатии, перезагрузит данные и покажет 10 вместо 4 только для этого конкретного раздела.Как вставить кнопку в нижней части каждого раздела UITableView?

Я начал работать над фреймворком для того, что происходит при нажатии кнопки. У меня просто возникают проблемы с синтаксисом для рендеринга кнопки внизу и отображения 10 строк только для этого раздела. Вот как у меня есть мой UITableView выкладывается до сих пор:

MatchCenterViewController.h:

#import <UIKit/UIKit.h> 
#import <Parse/Parse.h> 
#import "AsyncImageView.h" 
#import "SearchViewController.h" 
#import "WebViewController.h" 
#import "SLExpandableTableView.h" 

@interface MatchCenterViewController : UIViewController <UITableViewDataSource> 

@property (strong, nonatomic) NSString *itemSearch; 
@property (nonatomic, strong) NSArray *imageURLs; 
@property (strong, nonatomic) NSString *matchingCategoryCondition; 
@property (strong, nonatomic) NSString *matchingCategoryLocation; 
@property (strong, nonatomic) NSNumber *matchingCategoryMaxPrice; 
@property (strong, nonatomic) NSNumber *matchingCategoryMinPrice; 
@property (strong, nonatomic) NSArray *matchCenterArray; 
@property (strong, nonatomic) NSString *searchTerm; 
@property (strong, nonatomic) NSString *itemURL; 

@end 

MatchCenterViewController.m:

#import "MatchCenterViewController.h" 
#import <UIKit/UIKit.h> 

@interface MatchCenterViewController() <UITableViewDataSource, UITableViewDelegate> 
@property (nonatomic, strong) UITableView *matchCenter; 
@property (nonatomic, assign) BOOL matchCenterDone; 
@property (nonatomic, assign) BOOL hasPressedShowMoreButton; 
@end 

@implementation MatchCenterViewController 


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

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    _matchCenterDone = NO; 

    //self.matchCenter = [[SLExpandableTableView alloc] initWithFrame:self.view.bounds style:UITableViewCellStyleSubtitle]; 

    self.matchCenter = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewCellStyleSubtitle]; 

    self.matchCenter.frame = CGRectMake(0,50,320,self.view.frame.size.height-100); 
    _matchCenter.dataSource = self; 
    _matchCenter.delegate = self; 
    [self.view addSubview:self.matchCenter]; 

    _matchCenterArray = [[NSArray alloc] init]; 

} 

- (void)viewDidAppear:(BOOL)animated 
{ 
    self.matchCenterArray = [[NSArray alloc] init]; 

    UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]; 
    activityIndicator.center = CGPointMake(self.view.frame.size.width/2.0, self.view.frame.size.height/2.0); 
    [self.view addSubview: activityIndicator]; 

    [activityIndicator startAnimating]; 

    _matchCenterDone = NO; 

    // Disable ability to scroll until table is MatchCenter table is done loading 
    self.matchCenter.scrollEnabled = NO; 

    [PFCloud callFunctionInBackground:@"MatchCenter2" 
         withParameters:@{} 
           block:^(NSArray *result, NSError *error) { 

            if (!error) { 
             _matchCenterArray = result; 

             [activityIndicator stopAnimating]; 

             [_matchCenter reloadData]; 

             _matchCenterDone = YES; 
             self.matchCenter.scrollEnabled = YES; 
             NSLog(@"Result: '%@'", result); 
            } 
           }]; 

} 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return _matchCenterArray.count; 
} 

//the part where i setup sections and the deleting of said sections 

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { 
    return 21.0f; 
} 

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


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { 
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 21)]; 
    headerView.backgroundColor = [UIColor lightGrayColor]; 


    _searchTerm = [[[[_matchCenterArray objectAtIndex:section] objectForKey:@"Top 3"] objectAtIndex:0]objectForKey:@"Search Term"]; 

    UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(8, 0, 250, 21)]; 
    headerLabel.text = [NSString stringWithFormat:@"%@", _searchTerm]; 
    headerLabel.font = [UIFont boldSystemFontOfSize:[UIFont systemFontSize]]; 
    headerLabel.textColor = [UIColor whiteColor]; 
    headerLabel.backgroundColor = [UIColor lightGrayColor]; 
    [headerView addSubview:headerLabel]; 

    UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
    deleteButton.tag = section; 
    deleteButton.frame = CGRectMake(300, 2, 17, 17); 
    [deleteButton setImage:[UIImage imageNamed:@"xbutton.png"] forState:UIControlStateNormal]; 
    [deleteButton addTarget:self action:@selector(deleteButtonPressed:) forControlEvents:UIControlEventTouchUpInside]; 
    [headerView addSubview:deleteButton]; 
    return headerView; 

} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    NSDictionary *currentSectionDictionary = _matchCenterArray[section]; 
    NSArray *top3ArrayForSection = currentSectionDictionary[@"Top 3"]; 
    return top3ArrayForSection.count-1; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    // Initialize cell 
    static NSString *CellIdentifier = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (!cell) { 
     // if no cell could be dequeued create a new one 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 
    } 

    // No cell separators = clean design 
    tableView.separatorColor = [UIColor clearColor]; 

    // title of the item 
    cell.textLabel.text = _matchCenterArray[indexPath.section][@"Top 3"][indexPath.row+1][@"Title"]; 
    cell.textLabel.font = [UIFont boldSystemFontOfSize:14]; 

    // price of the item 
    cell.detailTextLabel.text = [NSString stringWithFormat:@"$%@", _matchCenterArray[indexPath.section][@"Top 3"][indexPath.row+1][@"Price"]]; 
    cell.detailTextLabel.textColor = [UIColor colorWithRed:0/255.0f green:127/255.0f blue:31/255.0f alpha:1.0f]; 

    // image of the item 
    NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:_matchCenterArray[indexPath.section][@"Top 3"][indexPath.row+1][@"Image URL"]]]; 
    [[cell imageView] setImage:[UIImage imageWithData:imageData]]; 

    return cell; 

} 


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    if (indexPath.row > 3 || self.hasPressedShowMoreButton){ 
     return 0; 
    } 
    else{ 
     return 65; 
    } 
} 


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    if (_matchCenterDone == YES) { 
     self.itemURL = _matchCenterArray[indexPath.section][@"Top 3"][indexPath.row][@"Item URL"]; 
     [self performSegueWithIdentifier:@"WebViewSegue" sender:self]; 
    } 
} 

-(IBAction)pressedShowMoreButton{ 
    self.hasPressedShowMoreButton = YES; 
    [self.matchCenter reloadData]; 
} 


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



#pragma mark - Navigation 

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{ 
    WebViewController *controller = (WebViewController *) segue.destinationViewController; 
    controller.itemURL = self.itemURL; 
} 


@end 

ответ

1

для этой функции вы можете использовать специальный UITableViewCell или нижний колонтитул UITableView

+0

Если я «Не ошибаюсь, это для создания нижнего колонтитула для всей таблицы, а не для отдельного нижнего колонтитула для каждого раздела, нет? Я хочу, чтобы каждый раздел имел свою собственную кнопку внизу. – Ghobs

0

Yo u можете использовать свойство tableFooterView.

Ниже, как я использую показать больше нагрузки вариант

UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 65)]; 
v.backgroundColor = [UIColor clearColor]; 

int mySiz = 0; 
// keep counter how many times load more is pressed.. initial is 0 (this is like index) 
mySiz = [startNumberLabel.text intValue]+1; 


// i have 15 bcz my index size is 15. 
if ([feeds count]>=(15*mySiz)) { 
    NSLog(@"showing button..."); 
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 
    [button setFrame:CGRectMake(10, 10, 296, 45)]; 
    [button setBackgroundImage:[UIImage imageNamed:localize(@"loadmore")] forState:UIControlStateNormal]; 
    [button addTarget:self action:@selector(loadMoreData:) forControlEvents:UIControlEventTouchUpInside]; 
    [v addSubview:button]; 
    mainTableView.tableFooterView = v; 
} else { 
    mainTableView.tableFooterView = nil; 
} 

[mainTableView reloadData]; 

Теперь настроить код в соответствии с вашей необходимостью ...

+0

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

0

Законченное делает это так:

// Create "more" button 
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section { 
    UIView *view = [[UIView alloc] initWithFrame:CGRectZero]; 
    view.backgroundColor = [UIColor whiteColor]; 

    self.moreButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
    self.moreButton.frame = CGRectMake(0, 0, 320, 44); 
    [self.moreButton setImage:[UIImage imageNamed:@"downarrow.png"] forState:UIControlStateNormal]; 
    [self.moreButton addTarget:self action:@selector(moreButtonSelected:) forControlEvents:UIControlEventTouchUpInside]; 
    [view addSubview:self.moreButton]; 

    return view; 
} 

// Load rest of items 
- (void)moreButtonSelected:(id)sender { 
    if (_hasPressedShowMoreButton == NO){ 
     self.hasPressedShowMoreButton = YES; 
    } 
    else if (_hasPressedShowMoreButton == YES){ 
     self.hasPressedShowMoreButton = NO; 
    } 

    [self.matchCenter reloadData]; 
} 
Смежные вопросы