IOS - How to create Custom Cell for Tableview?

Asked

Viewed 74 times

2

I want to make a custom cell for my Tableview. But it is presenting problems that I am not able to solve. It worked normally when I did with the standard cell, but when I did custom gave problem

I was using this explanation as help: http://www.appcoda.com/customize-table-view-cells-for-uitableview/

I made my cell this way..

Simpletablecell.xib and Simpletablecell. h:

inserir a descrição da imagem aqui

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 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' In case anyone knows how I can fix this, I thank you in advance.

  • 1

    The nib in case, is your interface file, which from what I understand is the MuralCell.xib, but your class is named after SimpleTableCell and it seems that the file name is MuralCellM.h. Anyway, I was very confused about these names, and if so, this is the reason. The error says that it cannot load a "nib" of name Simpletablecell.

  • Thank you Paulo, I’ll fix it right now! if I get or don’t notice soon.

  • You were right, there was conflict between the names, I corrected here and in the question too. But now it takes all the information from JSON and after that, it presents an error stating the problem I updated in the question.

  • 1

    Put a "breakpoint for all execptions" in the debug menu, then it stops at the line where the problem occurs. This way it is difficult to say what can be.

  • It is no longer presenting errors, but when I have compiled, it does not show any information in the list. The screen is all blank. I’m working on it to see if I can fix it. The only thing that appears after the execution I left informed on (Errors Presented) in the question

  • 1

    You need to implement the following method as well: - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; }

  • Thanks for the tip Luis, implemented at Viewcontroller. m but the problem mentioned earlier remained.

  • 1

    Never worked with cell creating XIB, I do it by Interfacebuilder even... have you ever tried to debug your code line by line to see where you are logging this error? I would guess that it is time to read the json that is not finding any key, but it may be time to load the XIB as well. Anyway, just debugging to solve.

  • The JSON are okay, Henrique, I was doing it now. I’m going to try to fix it tonight. Tomorrow I inform here if you have succeeded in any way find any solution, inform that the night I return here. Hug!

Show 4 more comments

1 answer

0


Well, the example I took as a basis, it was an old example, it didn’t even have a storyboard, just files. xib, I decided to do a new project and with the help of some web pages, I managed to do this way.

I used this page as a basis: http://www.makemegeek.com/custom-uitableviewcell-example-ios/

I changed the name Simpletablecell to Customcell.

was thus:

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 Viewcontroller to Muralviewcontroller.

Stayed that way:

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

This way it is working well, remembering that I had to use:

-Foundation.

-Coregraphics.framework

-Uikit.framework

And also at . storyboard, I added the datasource and delegate Outlets to Tableview

Browser other questions tagged

You are not signed in. Login or sign up in order to post.