IOS - How to create a custom TableView cell?

2

I want to make a custom cell for my TableView. But she's presenting problems that I can not solve. It worked normally when I did with the default cell, but when I did custom it gave problem

I was using this explanation to help: link

I made my cell this way ..

SimpleTableCell.xib and SimpleTableCell.h:

SimpleTableCell.m

import"SimpleTableCell.h"

@interface SimpleTableCell ()
@end
@implementation SimpleTableCell

@synthesize nome = _nome;
@synthesize texto = _texto;
@synthesize data = _data;
@synthesize foto = _foto;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
    }
    return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];
}

My ViewController (Where is the TableView), this way.

ViewController.m

#import "ViewController.h"
#import "SimpleTableCell.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //________________________
    _tabela.dataSource = self;
    _tabela.delegate = self;
    //________________________
    //Na ViewDidLoad eu pego um Json e armazenando seus dados em uma lista (lista manda dados para célula)
    _users = [[NSMutableArray alloc] init];

    NSURLRequest *requisicao = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.meuSite.com.br/mural/listener.php?a=10"]];
    NSData *resposta = [NSURLConnection sendSynchronousRequest:requisicao
                                             returningResponse:nil                  
                                                         error:nil];
    NSError *jsonParsingError = nil;
    NSArray *array = [NSJSONSerialization JSONObjectWithData: resposta options: nil error: &jsonParsingError];
    NSLog(@"result = %@", array.firstObject);
    int total = [array count];

    for (int x =0; x<total; x++) {
        [_users addObject:[array objectAtIndex:x]];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{//tamanho da lista
    return [_users count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"SimpleTableCell";
    SimpleTableCell *cell = (SimpleTableCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if (cell == nil) {
        NSLog(@"QUANDO COMPILO SÓ VEM ATÉ AQUI. . .");
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"SimpleTableCell" owner:self options:nil];
        NSLog(@"%d", 23);
        cell = [nib objectAtIndex:0];
        NSLog(@"%d", 3);
    }
    NSDictionary * usuario = [_users objectAtIndex:indexPath.row];
    cell.nome.text = [usuario objectForKey:@"nome"];
    cell.texto.text = [usuario objectForKey:@"texto"];
    cell.data.text = [usuario objectForKey:@"data"];
    NSString *img = @"http://diegocavalca.com/wp-content/uploads/2016/01/iphone_6_home_screen_hero.jpg";

    NSString *url_imagem = [NSString stringWithFormat:img];
    NSLog(@"%@", url_imagem);

    NSURL *url=[NSURL URLWithString:url_imagem];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
     {
         cell.foto.image =[UIImage imageWithData:data];
     }];
    return cell; 
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}
@end

ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UITableViewDataSource, UITableViewDelegate>
@property NSMutableArray * users;
@property NSIndexPath * selecionado;
@property (weak, nonatomic) IBOutlet UITableView *tabela;

@end

Error Presented. . .

- [NSNull length]: unrecognized selector sent to instance 0x381cf588 ' If anyone knows how I can resolve this, thank you in advance.

    
asked by anonymous 11.02.2016 / 18:40

1 answer

0

Well, the example that I took as a base was an old example, I did not have a storyboard, just .xib files, I decided to make a new project and with the help of some web pages, I managed to do it this way. >

I used this page as a base: link

I changed the name SimpleTableCell to CustomCell.

looks like this:

CustomCell.h

#import <UIKit/UIKit.h>

@interface CustomCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UILabel *name;
@property (weak, nonatomic) IBOutlet UILabel *dataS;
@property (weak, nonatomic) IBOutlet UITextView *texto;

@end

CustomCell.m

#import "CustomCell.h"

@implementation CustomCell
@synthesize name,imageView,dataS;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {}
    return self;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated{
    [super setSelected:selected animated:animated];
}

@end

I changed the name of the ViewController to MuralViewController.

It looks like this:

MuralViewController.h

#import <UIKit/UIKit.h>

@interface MuralViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>
{
    NSMutableArray *ImageArray;//foodImageArray
}
@property (weak, nonatomic) IBOutlet UITableView *tableViewObject;
@property NSMutableArray * users;

@end

MuralViewController.m

#import "MuralViewController.h"
#import "CustomCell.h"

@interface MuralViewController ()

@end

@implementation MuralViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    ImageArray = [[NSMutableArray alloc] initWithObjects:@"image0.png", nil];
    //ADICIONADO . . .

    _users = [[NSMutableArray alloc] init];//Array de objétos json pegados de um link. . .

    NSURLRequest *requisicao = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.meuSite.com.br/mural/listener.php?a=50"]];

    NSData *resposta = [NSURLConnection sendSynchronousRequest:requisicao
                                             returningResponse:nil error:nil];
    NSError *jsonParsingError = nil;
    NSArray *array = [NSJSONSerialization JSONObjectWithData: resposta options: nil error: &jsonParsingError];

    NSDictionary *resultado = [NSJSONSerialization JSONObjectWithData:resposta
                                                              options:0 error:&jsonParsingError];

    NSLog(@"result = %@", resultado);
    int total = [array count];
    for (int x =0; x<total; x++) {
        NSLog(@"%@", [array objectAtIndex:x]);
        [_users addObject:[array objectAtIndex:x]];//Armazena na lista os dados json. . .
    }
}

- (void)didReceiveMemoryWarning{[super didReceiveMemoryWarning];}

#pragma - mark UITableView Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_users count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 130;//define o tamanho em que a célula vai aparecer. . .
}

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

    CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if (cell == nil)
    {
        NSArray *nibArray = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
        cell = [nibArray objectAtIndex:0];
    }

    NSDictionary * usuario = [_users objectAtIndex:indexPath.row];

    //ALOCA DADOS EM UMA STRING. . .    
    NSString *nome345 = [usuario objectForKey:@"nome"];
    NSString *data = [usuario objectForKey:@"data"];
    NSString *textok = [usuario objectForKey:@"texto"];

    nome345 = [NSString stringWithFormat:@"%@", nome345];//Tive que sobreescrever, quando mandava direto dava eero no if logo abaixo. . .
    NSLog(@"%@", nome345);

    //ESCREVE DADOS NA CÉLULA. . .
    if([nome345 isEqualToString:@"<null>"]){//Se o nome for null, ele carrega a imagem no lugar no nome, assim nunca vai ter nome e imagem juntos. . .
        cell.imageView.image = [UIImage imageNamed:[ImageArray objectAtIndex:0]];
    }else{
        cell.Name.text = [NSString stringWithFormat:@"%@", nome345];
    }

    cell.dataS.text = [NSString stringWithFormat:@"%@", data];
    cell.texto.text = [NSString stringWithFormat:@"%@", textok];
    return cell;
}
@end

In this way it is working fine, remembering that I had to use:

-Foundation.framework

-CoreGraphics.framework

-UIKit.framework

And also in the .storyboard, I added the DataSource and delegate Outlets to the TableView

    
17.02.2016 / 19:30