oscarimonbox
12/29/2015 - 11:21 AM

0tableview Preparación TableView básico

Preparación TableView básico

Añadir delegates: UITableViewDataSource, UITableViewDelegate

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
        
        tableView.register(UINib(nibName: "TargetCell", bundle: nil), forCellReuseIdentifier: "TargetCell")
        
        //QUITAMOS EL SEPARADOR
        tableView.separatorStyle = UITableViewCell.SeparatorStyle.none;
        
        if #available(iOS 15, *) {
          tableView.sectionHeaderTopPadding = 0
        }
        
    }
        
    // MARK: - TableView
    
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if(period == nil){
            return 0;
        }
        return period!.stores.count;
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        if(period == nil){
            return 0;
        }
        return 1;
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return CGFloat(AppConstants.CellHeight.RankingCell);
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return CGFloat(AppConstants.Dimensions.RankingHeight);
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        
        let rect = CGRect(
            origin: CGPoint(x: 0, y: 0),
            size: CGSize(width: self.tableView.frame.size.width, height: 70)
        )
        let header = PeriodHeader.init(frame: rect);
        
        let df = DateFormatter();
        df.dateFormat = "dd/MM/yyyy";
        
        let startDate = df.string(from: period?.start as! Date);
        let endDate = df.string(from: period?.end as! Date);
        
        //header.lblDate.text = "\(startDate) - \(endDate)";
        
        header.lblDate.text = String(format: "fromDateToDate".localized, startDate, endDate);
        header.lblTitle.text = period?.name;
        
        
        let tapCalendar = UITapGestureRecognizer(target: self, action: #selector(self.onCalendarPressed(_:)))
        header.addGestureRecognizer(tapCalendar)
        header.isUserInteractionEnabled = true
        
        return header;
        
        
        
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let identifier = "TargetCell"
        let cell: TargetCell! = tableView.dequeueReusableCell(withIdentifier: identifier) as? TargetCell
        
        let stores = period?.stores.sorted(by: { $0.salesVsTarget > $1.salesVsTarget })
        
        let store = stores?[indexPath.row];
        
        if(indexPath.row % 2 == 0){
            cell.backgroundColor = UIColor(rgb: AppConstants.Colors.gray);
        }
        else{
            cell.backgroundColor = UIColor.white;
        }
        
        cell.selectionStyle = .none
        
        cell.lblRanking.text = "#\(indexPath.row+1)";
        cell.lblTarget.text = "\(store!.storeName)";
        cell.lblPercentage.text = "\(store!.salesVsTarget)%";

        return cell;
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        selectedIndex = indexPath.row;
        self.performSegue(withIdentifier: "showPeriod", sender: self);
    }
1) en el .h de la clase indicar el delegate y datasource
@interface LOMenuViewController : LOViewController <UITableViewDataSource, UITableViewDelegate>

2) en viewDidLoad asignar:
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //Asignamos DataSource y Delegate
    _tableView.dataSource=self;
    _tableView.delegate=self;
    
    //Asociamos el XIB que incrustaremos
    [self.tableView registerClass:LOMenuFamilyTableViewCell.class forCellReuseIdentifier:@"LOMenuFamilyTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"LOMenuFamilyTableViewCell" bundle:nil] forCellReuseIdentifier:@"LOMenuFamilyTableViewCell"];
    //Quitamos separador
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
}

3) Implementar viewWillAppear
-(void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}

4) Implementar métodos de sección
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [[LOApplicationModel sharedInstance].family count];
}

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

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    LOSettingsFamilyHeaderSectionView * h = [[LOSettingsFamilyHeaderSectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, MENU_FAMILY_MEMBERS_HEIGHT)];
    
    h.lblMyFamily.text = NSLocalizedString(@"General_MyFamily", nil);
    h.lblNumberOfFamilyMembers.text = [NSString stringWithFormat:@"%d %@", [[LOApplicationModel sharedInstance].family count],NSLocalizedString(@"Settings_ChildDevicesLinked",nil)];
    return h;
}

5) Implementar métodos de celda:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 60;
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    LOMenuFamilyTableViewCell *familyCell;
    
    LOChild* child = [[LOApplicationModel sharedInstance].family objectAtIndex:indexPath.row];
    NSString *cellIdentifierFamily = @"LOMenuFamilyTableViewCell";
    familyCell = [tableView dequeueReusableCellWithIdentifier:cellIdentifierFamily];
    familyCell.lblNameFamilyMember.text = child.name;
    
    [familyCell.imgPhotoFamilyMember sd_setImageWithURL:child.photoURL placeholderImage:[UIImage imageNamed:@"profileBlank"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        if(image){
            [familyCell.imgPhotoFamilyMember setImage:image];
        }
    }];
    
    
    return familyCell;
}