[ios] Creating a UITableView Programmatically

I have an application in Xcode 4.6 which uses storyboards. I added a UITableView to a view controller class, which worked as expected. However, when I tried deleting the UITableView in the storyboard and adding it back into the same class programmatically, I ran into two specific problems:

1) Although I set the UITableViewCell type to be of type subtitle, the detail label no longer appears.

2) The segue that should occur when I select a cell does not occur, and prepare segue is not even being called, indicating that no message is being sent to the table view when a cell is selected.

Here is the relevant code:

@interface StatsTableViewController () <UITableViewDataSource, UITableViewDelegate>
@property (strong, nonatomic) UITableView *tableView;

@end

@implementation StatsTableViewController

-(UITableView *)makeTableView
{
    CGFloat x = 0;
    CGFloat y = 50;
    CGFloat width = self.view.frame.size.width;
    CGFloat height = self.view.frame.size.height - 50;
    CGRect tableFrame = CGRectMake(x, y, width, height);

    UITableView *tableView = [[UITableView alloc]initWithFrame:tableFrame style:UITableViewStylePlain];

    tableView.rowHeight = 45;
    tableView.sectionFooterHeight = 22;
    tableView.sectionHeaderHeight = 22;
    tableView.scrollEnabled = YES;
    tableView.showsVerticalScrollIndicator = YES;
    tableView.userInteractionEnabled = YES;
    tableView.bounces = YES;

    tableView.delegate = self;
    tableView.dataSource = self;

    return tableView;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.tableView = [self makeTableView];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"newFriendCell"];
    [self.view addSubview:self.tableView];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"newFriendCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    if (cell == nil) 
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }

    Friend *friend = [self.fetchedResultsController objectAtIndexPath:indexPath];

     **//THIS DATA APPEARS**
    cell.textLabel.text = friend.name;
    cell.textLabel.font = [cell.textLabel.font fontWithSize:20];
    cell.imageView.image = [UIImage imageNamed:@"icon57x57"];

    **//THIS DATA DOES NOT APPEAR**
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%i Games", friend.gameCount];
    cell.detailTextLabel.textColor = [UIColor lightGrayColor];

    return cell;
}

 -(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self performSegueWithIdentifier:@"detailsView" sender:self];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
      //I set the segue identifier in the interface builder
     if ([segue.identifier isEqualToString:@"detailsView"])
     {

         NSLog(@"segue"); //check to see if method is called, it is NOT called upon cell touch

         NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
         ///more code to prepare next view controller....
     }
}

I am not sure what I am forgetting to do so that I can solve these two issues. Any help is appreciated.

This question is related to ios objective-c xcode uitableview

The answer is


- (void)viewDidLoad {
     [super viewDidLoad];
     arr=[[NSArray alloc]initWithObjects:@"ABC",@"XYZ", nil];
     tableview = [[UITableView alloc]initWithFrame:tableFrame style:UITableViewStylePlain];   
     tableview.delegate = self;
     tableview.dataSource = self;
     [self.view addSubview:tableview];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return arr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCell"];

    if(cell == nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MyCell"];
    }

    cell.textLabel.text=[arr objectAtIndex:indexPath.row];

    return cell;
}

vc.m

#import "ViewController.h"

import "secondViewController.h"

 @interface ViewController ()
 {

NSArray *cityArray;
NSArray *citySubTitleArray;
NSArray *cityImage;
NSInteger selectindexpath;

}
@end

 @implementation ViewController

 - (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

cityArray = [[NSArray 
alloc]initWithObjects:@"Coimbatore",@"Salem",@"Chennai",nil];

citySubTitleArray = [[NSArray alloc]initWithObjects:@"1",@"2",@"3", nil];
cityImage = [[NSArray alloc]initWithObjects:@"12-300x272.png"
 , @"380267_70d232fc33b44d4ebe7b42bbe63ee9be.png",@"apple-logo_318
 -40184.png", nil];

 }


 #pragma mark - UITableView Data Source

 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
 {
return 1;

 }

 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection 
 :(NSInteger)section
  {
return cityImage.count;
 }

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

UITableViewCell *cell =
 [tableView dequeueReusableCellWithIdentifier:cellId];

if (cell == nil)
{
    cell = [[UITableViewCell 
  alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellId];
}

cell.textLabel.text = [cityArray objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [citySubTitleArray objectAtIndex:indexPath.row];
cell.imageView.image = [UIImage imageNamed:
 [cityImage objectAtIndex:indexPath.row]];




 //    NSData *data = [[NSData alloc]initWithContentsOfURL:
 [NSURL URLWithString:@""]];

 //    cell.imageView.image = [UIImage imageWithData:data];

return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath
:  (NSIndexPath *)indexPath
 {
 NSLog(@"---- %@",[cityArray objectAtIndex:indexPath.row]);
 NSLog(@"----- %@",[cityImage objectAtIndex:indexPath.row]);
 selectindexpath=indexPath.row;
 [self performSegueWithIdentifier:@"second" sender:self];
  }

  #pragma mark - Navigation

 // In a storyboard-based application, you will often want to do a little p
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
    {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 if ([segue.identifier isEqualToString:@"second"])
 {
    secondViewController *object=segue.destinationViewController;
    object.cityName=[cityArray objectAtIndex:selectindexpath];
    object.cityImage=[cityImage objectAtIndex:selectindexpath];
       }
 }


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

 @end

vc.m

 #import <UIKit/UIKit.h>

 @interface ViewController : UIViewController<UITableViewDataSource
  , UITableViewDelegate>
 @property (strong, nonatomic) IBOutlet UITableView *cityLabelList;

@end

sv.m

 #import <UIKit/UIKit.h>

@interface secondViewController : UIViewController
@property(strong, nonatomic) NSString *cityName;
 @property(strong,nonatomic)NSString *cityImage;
@end

sv.h

#import "secondViewController.h"

 @interface secondViewController ()

 @property (strong, nonatomic) IBOutlet UILabel *lbl_desc;
 @property (strong, nonatomic) IBOutlet UIImageView *img_city;
    @end

 @implementation secondViewController

 - (void)viewDidLoad {
 [super viewDidLoad];
// Do any additional setup after loading the view.
self.title=self.cityName;


if ([self.cityName isEqualToString:@"Coimbatore"])
{


    self.lbl_desc.text=@"Coimbatore city";
    self.img_city.image=[UIImage imageNamed:
    [NSString stringWithFormat:@"%@",self.cityImage]];
}
 else if ([self.cityName isEqualToString:@"Chennai"])
 {

    self.lbl_desc.text= @"Chennai City Gangstar";
    self.img_city.image=[UIImage imageNamed:
   [NSString stringWithFormat:@"%@",self.cityImage]];

   }
  else
   {


    self.lbl_desc.text= @"selam City";
    self.img_city.image=[UIImage imageNamed:
   [NSString stringWithFormat:@"%@",self.cityImage]];

   }
 }

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

- (void)viewDidLoad
{
    [super viewDidLoad];
    tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;

    tableView.backgroundColor = [UIColor grayColor];

    // add to superview
    [self.view addSubview:tableView];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)theTableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)theTableView numberOfRowsInSection:    (NSInteger)section
{
    return 1;
}

// the cell will be returned to the tableView
- (UITableViewCell *)tableView:(UITableView *)theTableView  cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"HistoryCell";

    // Similar to UITableViewCell, but 
    UITableViewCell *cell = (UITableViewCell *)[theTableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.descriptionLabel.text = @"Testing";
    return cell;
}

- (NSInteger)tableView:(UITableView *)theTableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)theTableView  cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"HistoryCell";

    UITableViewCell *cell = (UITableViewCell *)[theTableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.descriptionLabel.text = @"Testing";
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //Code for selection.
}

these are UITableView delegate methods.


#import "ViewController.h"

@interface ViewController ()

{

    NSMutableArray *name;

}

@end


- (void)viewDidLoad 

{

    [super viewDidLoad];
    name=[[NSMutableArray alloc]init];
    [name addObject:@"ronak"];
    [name addObject:@"vibha"];
    [name addObject:@"shivani"];
    [name addObject:@"nidhi"];
    [name addObject:@"firdosh"];
    [name addObject:@"himani"];

    _tableview_outlet.delegate = self;
    _tableview_outlet.dataSource = self;

}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

return [name count];

}


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

{

    static NSString *simpleTableIdentifier = @"cell";

    UITableViewCell *cell = [tableView       dequeueReusableCellWithIdentifier:simpleTableIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    }

    cell.textLabel.text = [name objectAtIndex:indexPath.row];
    return cell;
}

Creating a tableview using tableViewController .

import UIKit

class TableViewController: UITableViewController
{
    let tableViewModel = TableViewModel()
    var product: [String] = []
    var price: [String] = []
    override func viewDidLoad()
    {
        super.viewDidLoad()
        self.tableView.contentInset = UIEdgeInsetsMake( 20, 20 , 0, 0)
        let priceProductDetails = tableViewModel.dataProvider()

        for (key, value) in priceProductDetails
        {
            product.append(key)
            price.append(value)
        }
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return product.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let cell = UITableViewCell(style: .Value1, reuseIdentifier: "UITableViewCell")
        cell.textLabel?.text = product[indexPath.row]
        cell.detailTextLabel?.text = price[indexPath.row]
        return cell
    }

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {
        print("You tapped cell number \(indexPath.row).")
    }
}

sample table

 #import "StartreserveViewController.h"
 #import "CollectionViewController.h"
 #import "TableViewCell1.h"
@interface StartreserveViewController ()


{
NSArray *name;
NSArray *images;
NSInteger selectindex;

}

@end

@implementation StartreserveViewController

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.

self.view.backgroundColor = [UIColor blueColor];
_startReservetable.backgroundColor = [UIColor blueColor];


name = [[NSArray alloc]initWithObjects:@"Mobiles",@"Costumes",@"Shoes", 
nil];
images = [[NSArray 
 alloc]initWithObjects:@"mobilestitle.jpg",@"costumetitle.jpeg", 
 @"shoestitle.png",nil];



  }

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

pragma mark - UiTableview Datasource

 -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
 {
return 1;
 }

 -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:
 (NSInteger)section
 {
return 3;
 }

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


static NSString *cellId = @"tableview";

TableViewCell1  *cell =[tableView dequeueReusableCellWithIdentifier:cellId];


cell.cellTxt .text = [name objectAtIndex:indexPath.row];

cell.cellImg.image = [UIImage imageNamed:[images 
objectAtIndex:indexPath.row]];

return cell;



 }


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:
(NSIndexPath *)indexPath
 {
selectindex = indexPath.row;
[self performSegueWithIdentifier:@"second" sender:self];
}



   #pragma mark - Navigation

 // In a storyboard-based application, you will often want to do a little     
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

if ([segue.identifier isEqualToString:@"second"])

  {
    CollectionViewController *obj = segue.destinationViewController;
           obj.receivename = [name objectAtIndex:selectindex];

  }



// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}

 @end

.h

#import <UIKit/UIKit.h>

@interface StartreserveViewController :      
UIViewController<UITableViewDelegate,UITableViewDataSource>    
@property (strong, nonatomic) IBOutlet UITableView *startReservetable;

 @end

You might be do that its works 100% .

- (void)viewDidLoad
{
    [super viewDidLoad];
    // init table view
    tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];

    // must set delegate & dataSource, otherwise the the table will be empty and not responsive
    tableView.delegate = self;
    tableView.dataSource = self;

    tableView.backgroundColor = [UIColor cyanColor];

    // add to canvas
    [self.view addSubview:tableView];
}

#pragma mark - UITableViewDataSource
// number of section(s), now I assume there is only 1 section
- (NSInteger)numberOfSectionsInTableView:(UITableView *)theTableView
{
    return 1;
}

// number of row in the section, I assume there is only 1 row
- (NSInteger)tableView:(UITableView *)theTableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

// the cell will be returned to the tableView
- (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"HistoryCell";

    // Similar to UITableViewCell, but 
    JSCustomCell *cell = (JSCustomCell *)[theTableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[JSCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    // Just want to test, so I hardcode the data
    cell.descriptionLabel.text = @"Testing";

    return cell;
}

#pragma mark - UITableViewDelegate
// when user tap the row, what action you want to perform
- (void)tableView:(UITableView *)theTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"selected %d row", indexPath.row);
}

@end

Examples related to ios

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Examples related to objective-c

Adding a UISegmentedControl to UITableView Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Warp \ bend effect on a UIView? Use NSInteger as array index Detect if the device is iPhone X Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3 ITSAppUsesNonExemptEncryption export compliance while internal testing? How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem? Change status bar text color to light in iOS 9 with Objective-C

Examples related to xcode

Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64 iPhone is not available. Please reconnect the device Make a VStack fill the width of the screen in SwiftUI error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65 The iOS Simulator deployment targets is set to 7.0, but the range of supported deployment target version for this platform is 8.0 to 12.1 Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools) Xcode 10: A valid provisioning profile for this executable was not found Xcode 10, Command CodeSign failed with a nonzero exit code

Examples related to uitableview

Adding a UISegmentedControl to UITableView make UITableViewCell selectable only while editing How to fix Error: this class is not key value coding-compliant for the key tableView.' UITableView example for Swift Swift - how to make custom header for UITableView? How to insert new cell into UITableView in Swift How to detect tableView cell touched or clicked in swift Dynamic Height Issue for UITableView Cells (Swift) UIButton action in table view cell How to get the indexpath.row when an element is activated?