Search code examples
iosobjective-cuinavigationcontrolleruibutton

What will be the code for navigating from button on UITableviewCell to other view controller?


Here is my table view,

enter image description here

Initially, it looks like this, when I click on in this cell then it will expand

enter image description here

My Question: I added a button to UITableviewCell and given action for it. When I click on attachment button then It has to navigate to next view. I tried below code but it works for UIViewcontroller, not for UITableViewCell.

AttachmentView *attach=[self.storyboard instantiateViewControllerWithIdentifier:@"attachViewId"];

    [self.navigationController pushViewController:attach animated:YES];

How to achieve this?

here is my ConversationTableViewCell.h file,

 #import <UIKit/UIKit.h>

    @interface ConversationTableViewCell : UITableViewCell

    @property (weak, nonatomic) IBOutlet UIImageView *profilePicView;

    @property (weak, nonatomic) IBOutlet UILabel *clientNameLabel;

    @property (weak, nonatomic) IBOutlet UILabel *internalNoteLabel;

    @property (weak, nonatomic) IBOutlet UILabel *timeStampLabel;

    -(void)setUserProfileimage:(NSString*)imageUrl;
    @property (weak, nonatomic) IBOutlet UIWebView *webView;
    @property (weak, nonatomic) IBOutlet UIView *view1;

    - (IBAction)clickedOnAttachment:(id)sender;

and this is ConversationTableViewCell.m file code,

 #import "HexColors.h"
    #import "ConversationTableViewCell.h"
    #import <SDWebImage/UIImageView+WebCache.h>
    #import "AttachmentViewController.h"

    @implementation ConversationTableViewCell

    - (void)awakeFromNib {
        [super awakeFromNib];

    }

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

      }

    -(void)setUserProfileimage:(NSString*)imageUrl
    {
       // self.profilePicView.layer.borderWidth=1.25f;
        self.profilePicView.layer.borderColor=[[UIColor hx_colorWithHexRGBAString:@"#0288D1"] CGColor];
        [self.profilePicView sd_setImageWithURL:[NSURL URLWithString:imageUrl]
                               placeholderImage:[UIImage imageNamed:@"default_pic.png"]];

    }

    - (IBAction)clickedOnAttachment:(id)sender {

     //   NSLog(@"CLciked...!");

        UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main"
                                                                 bundle: nil];

        AttachmentViewController * attach=[mainStoryboard instantiateViewControllerWithIdentifier:@"attachId"];

        [self.navigation];
    }
    @end

This is view controller code,

// this is ConversationTableViewCell view controllers .m file

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

    ConversationTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"ConvTableViewCell"];

    if (cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ConversationTableViewCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    NSDictionary *finaldic=[mutableArray objectAtIndex:indexPath.row];



@try{


    attachmentArray=[finaldic objectForKey:@"attach"];

    if ([attachmentArray count] != 0){

        NSIndexPath *path;
        NSDictionary *attachDictionary=[attachmentArray objectAtIndex:path.row];
        //   NSLog(@"Attchment Dict is: %@",attachDictionary);

        NSString *numStr = [NSString stringWithFormat:@"%@", [attachDictionary objectForKey:@"file"]];
            }else
    {
        NSLog(@"EMpty aaray");
    }



    cell.timeStampLabel.text=[utils getLocalDateTimeFromUTC:[finaldic objectForKey:@"created_at"]];


    NSString *body= [finaldic objectForKey:@"body"]; 
    NSRange range = [body rangeOfString:@"<body"];

    if(range.location != NSNotFound) {
        // Adjust style for mobile
        float inset = 40;
        NSString *style = [NSString stringWithFormat:@"<style>div {max-width: %fpx;}</style>", self.view.bounds.size.width - inset];
        body = [NSString stringWithFormat:@"%@%@%@", [body substringToIndex:range.location], style, [body substringFromIndex:range.location]];
    }
    cell.webView.translatesAutoresizingMaskIntoConstraints = NO;
    [cell.webView loadHTMLString:body baseURL:nil];



   //NSString *system= @"System";
   NSString *fName=[finaldic objectForKey:@"first_name"];
   NSString *lName=[finaldic objectForKey:@"last_name"];
   NSString *userName=[finaldic objectForKey:@"user_name"];

   [Utils isEmpty:fName];
   [Utils isEmpty:lName];
   [Utils isEmpty:userName];



     if  ([Utils isEmpty:fName] && [Utils isEmpty:lName]){
         if(![Utils isEmpty:userName]){
        userName=[NSString stringWithFormat:@"%@",[finaldic objectForKey:@"user_name"]];
             cell.clientNameLabel.text=userName;
         }else cell.clientNameLabel.text=@"System";
    }
    else if ((![Utils isEmpty:fName] || ![Utils isEmpty:lName]) || (![Utils isEmpty:fName] && ![Utils isEmpty:lName]))
    {
       NSString * fName12=[NSString stringWithFormat:@"%@ %@",fName,lName];

        cell.clientNameLabel.text=fName12;

    }

// prifile image
        if([[finaldic objectForKey:@"profile_pic"] hasSuffix:@"system.png"] || [[finaldic objectForKey:@"profile_pic"] hasSuffix:@".jpg"] || [[finaldic objectForKey:@"profile_pic"] hasSuffix:@".jpeg"] || [[finaldic objectForKey:@"profile_pic"] hasSuffix:@".png"] )
        {
            [cell setUserProfileimage:[finaldic objectForKey:@"profile_pic"]];
        }
         else if(![Utils isEmpty:fName])
        {
            [cell.profilePicView setImageWithString:fName color:nil ];
        }
       else
       {
           [cell.profilePicView setImageWithString:userName color:nil ];
       }


}@catch (NSException *exception)
    {
        [utils showAlertWithMessage:exception.name sendViewController:self];
        NSLog( @"Name: %@", exception.name);
        NSLog( @"Reason: %@", exception.reason );
       // return;
    }
    @finally
    {
        NSLog( @" I am in cellForROwAtIndexPath method in Conversation ViewController" );

    }


    return cell;
}

Solution

  • self.navigationController is not available in ConversationTableViewCell class.

    In order to push a new instance of UIViewController on click of cell/ a button on a cell, you should use Delegation design pattern.

    Example -

    //ConversationTableViewCell.h
    
    @protocol ConversationTableViewCellDelegate;
    
    @interface ConversationTableViewCell : UITableViewCell
    
    @property (assign, nonatomic) id < ConversationTableViewCellDelegate > delegate;
    
    @end
    
    @protocol ConversationTableViewCellDelegate <NSObject>
    
    @optional
    
    - (void)buttonTouchedForCell:(ConversationTableViewCell *)cell;
    
    @end
    
    //ConversationTableViewCell.m
    @implementation ConversationTableViewCell
    
    @synthesize delegate = _delegate;
    
    - (IBAction)clickedOnAttachment:(id)sender {
            if ([self.delegate respondsToSelector:@selector(buttonTouchedForCell:)])
            [self.delegate buttonTouchedForCell:self];
        }
    @end
    
    
    @interface YourController : UIViewController <ConversationTableViewCellDelegate>
    
    @end
    
    @implementation YourController
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
     ConversationTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"ConvTableViewCell"];
    
            if (cell == nil)
            {
               NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ConversationTableViewCell" owner:self options:nil];
               cell = [nib objectAtIndex:0];
            }
    
            [cell setDelegate:self];
    
            // cell related code
    
            return cell;
        }
    
        - (void) buttonTouchedForCell:(ConversationTableViewCell *)cell {
    
            NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
            AttachmentView *attach=[self.storyboard instantiateViewControllerWithIdentifier:@"attachViewId"];
            [self.navigationController pushViewController:attach animated:YES];
        }
    
    @end