I'm trying to build a table with cells that list an array in UILabels. So each cell will have its size and amount of labels determined by the number of objects in that array. However, I'm running into an issue where the content is initially input correctly, but then as the table cells get recycled during the scroll, the content doesn't clear.
Here's my entire implementation. If someone could please give me an explanation as to how I can prevent the labels from being retained during the recycling process I'd really appreciate it. Thank you.
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate> {
UITableView *tableView;
}
#end
ViewController.m
#import "ViewController.h"
#import "CustomCell.h"
#interface ViewController () {
NSArray *myTableArray;
}
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Set up View
self.view = [[UIView alloc] initWithFrame: [UIScreen mainScreen].applicationFrame];
self.view.backgroundColor = [UIColor whiteColor];
self.view.clipsToBounds = YES;
self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
// Set up Table
CGRect frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
tableView = [[UITableView alloc] initWithFrame:frame style:UITableViewStylePlain];
tableView.backgroundColor = [UIColor clearColor];
tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
tableView.dataSource = self;
tableView.delegate = self;
[tableView registerClass:[CustomCell class] forCellReuseIdentifier:#"CustomCell"];
[self.view addSubview:tableView];
//Set up dummy array for cells (in my actual app I'm pulling from Core Data)
NSArray *cell1 = [[NSArray alloc]initWithObjects:#"Some Text", nil];
NSArray *cell2 = [[NSArray alloc]initWithObjects:#"Different", #"Text", nil];
NSArray *cell3 = [[NSArray alloc]initWithObjects:#"Lorem...", nil];
NSArray *cell4 = [[NSArray alloc]initWithObjects:#"Thanks", #"for your", #"help", nil];
NSArray *cell5 = [[NSArray alloc]initWithObjects:#"A bit more", #"text", nil];
NSArray *cell6 = [[NSArray alloc]initWithObjects:#"Bunch of", #"junk text", nil];
NSArray *cell7 = [[NSArray alloc]initWithObjects:#"So long", #"and thanks", #"for all", #"the fish", nil];
NSArray *cell8 = [[NSArray alloc]initWithObjects:#"Ipsum..", nil];
NSArray *cell9 = [[NSArray alloc]initWithObjects:#"Peter Pan", #"killed", #"The Lost Boys", nil];
NSArray *cell10 = [[NSArray alloc]initWithObjects:#"All Dogs", #"Go to Heaven", #"Disney", nil];
myTableArray = [[NSArray alloc]initWithObjects:cell1, cell2, cell3, cell4, cell5, cell6, cell7, cell8, cell9, cell10, nil];
NSLog(#"%#",myTableArray);
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return myTableArray.count;
}
- (CGFloat)tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSArray *arr = [myTableArray objectAtIndex:indexPath.row];
return 60 * arr.count;
}
- (UITableViewCell*)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"CustomCell";
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
if (!cell)
cell = [[CustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
// Set up the labels
[cell setLabels:myTableArray[indexPath.row]];
return cell;
}
#end
CustomCell.h
#import <UIKit/UIKit.h>
#interface CustomCell : UITableViewCell
- (void)setLabels:(NSArray *)labels;
#end
CustomCell.m
#import "CustomCell.h"
#implementation CustomCell
- (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];
// Configure the view for the selected state
}
- (void)setLabels:(NSArray *)labels {
int labelHeight = 60;
int y = 0;
for (NSString *string in labels) {
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, y, self.bounds.size.width-20, labelHeight)];
label.text = string;
label.font = [label.font fontWithSize:20];
y += labelHeight;
[self.contentView addSubview:label];
}
}
#end
In your CustomCell.m:
- (void)prepareForReuse {
[super prepareForReuse];
for(UIView *subview in [self.contentView subviews]) {
[subview removeFromSuperview];
}
}
prepareForReuse is a method called on cells as the table view is dequeuing them for reuse.
I'll assume that you've minimized what you're actually doing to a very simplistic example, because otherwise, as Leo Natan has suggested, you should simply be using the existing labels.
That's because you are adding a new UILabel subview without removing the old one.
Why are you adding new labels? Use the already existing label. Since you are using UITableViewCellStyleDefault, the cell already contains several labels. Use self.textLabel.text = string instead.
If you wish to keep using a custom label, you should remove all subviews in the cell's prepareForReuse (don't forget to call the super implementation of prepareForReuse). Just remember, that since you have defined the cell as UITableViewCellStyleDefault, it will have other subviews that you should not remove.
You should remove all labels before add labels in reused cell.
- (UITableViewCell*)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"CustomCell";
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
if (!cell)
cell = [[CustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
for (UIView * subView in [cell.contentView subviews]) {
if ([subView isKindOfClass:[UILabel class]]) {
[subView removeFromSuperview] ;
}
}
// Set up the labels
[cell setLabels:myTableArray[indexPath.row]];
return cell;
}
Related
I've created a custom UITableViewCell and i need a bottom line separator for each cell then i put the separator in init method of my custom tableViewCell
This is my TableView code :
#import "Telegram_TableViewController.h"
#import "Custom_TableViewCell.h"
#interface Telegram_TableViewController ()
#end
#implementation Telegram_TableViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.array =[[NSMutableArray alloc] init];
for (int i=0; i<200; i++) {
[self.array addObject:[NSString stringWithFormat:#"item %i" ,i]];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.array count] ;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *Identifier = #"CELL";
Custom_TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Identifier];
cell = [[Custom_TableViewCell alloc] init];
UILabel *txt = [[UILabel alloc]init];
txt.text = [NSString stringWithFormat:#"Item " ] ;
cell.textLabel.text = [self.array objectAtIndex:indexPath.row];
return cell;
}
and my custom TableViewCell code :
#import "Custom_TableViewCell.h"
#implementation Custom_TableViewCell
- (void)awakeFromNib {
// Initialization code
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
-(id)init
{
self = [super init];
if (self) {
UIEdgeInsets insets = self.separatorInset;
self.separatorInset = UIEdgeInsetsMake(0.0, 0.0,insets.bottom + 6.0, 0.0);
self.separatorInset = insets;
}
return self;
}
There is no error but it doesn't work. How can i fix it?
Thanks in advance.
Clean init method in Custom_TableViewCell and see if this helps.
In Telegram_TableViewController:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *Identifier = #"CELL";
Custom_TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Identifier];
cell = [[Custom_TableViewCell alloc] init];
UILabel *txt = [[UILabel alloc]init];
txt.text = [NSString stringWithFormat:#"Item " ] ;
cell.textLabel.text = [self.array objectAtIndex:indexPath.row];
[tableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
[tableView setSeparatorColor:[UIColor blackColor]];
return cell;
}
And make sure the color of the separator is different than the color of the cell itself.
Use this code in your cell,s .h file
#property (nonatomic,strong) UIView* cellSeperatorView;
and in .m file
-(UIView *)cellSeperatorView{
if (!cellSeperatorView) {
self.cellSeperatorView = [[UIView alloc] initWithFrame:CGRectZero];
[self.cellSeperatorView setBackgroundColor:[UIColor lightGrayColor]];
[self addSubview:self.cellSeperatorView];
}
return cellSeperatorView;
}
-(void)prepareForReuse{
self.cellSeperatorView = nil;
}
-(void)layoutSubviews{
[super layoutSubviews];
[self.cellSeperatorView setFrame:CGRectMake(0, 0, 500, 1)];
}
and call this method in your tableview class in - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)..
UITableViewCellClass *cell = (UITableViewCellClass *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (!cell) {
cell = [[UITableViewCellClass alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
cell.cellSeperatorView.hidden = (indexPath.row == ([self.yourtableViewArray numberOfRowsInSection:indexPath.section]));
and in you viewdidload method add this
[self.yourtableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
i think this can help you for making separator..
You'd better register in the method viewDidLoad when you want to custom cell. [self.tableView registerClass:[Custom_TableViewCell class] forCellReuseIdentifier:Identifier];
What is cell = [[Custom_TableViewCell alloc] init];? You are not reusing the cell, but initiate every time. Just do not write this line.
The right way to overwrite the init method of tableViewCell to is rewrite - (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
Now you can see the tableView correctly, but I do not understand a bottom line separator, just write what you want in the method initWithStyle.
I have 7 rows in my database. I confirmed that all of the data is successfully coming over to the iOS side by NSLog the postArray which gives 7. However when I run my app, it will only display the first 5 rows, and then the first 2 rows instead of the 6th and 7th row from my database. Also when I NSLog the actual text from my 6th and 7th text view the correct text is in there... Why is it repeating after 5 rows? Thank you. Here is my code:
#import "DailyViewController.h"
#import "Post.h"
#interface DailyViewController ()
#end
#implementation DailyViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// View background
[self.view setBackgroundColor:[UIColor colorWithRed:(255/255.0) green:(221/255.0) blue:(85/255.0) alpha:1.0f]];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://example.org/getPosts.php"]];
NSData *data = [NSData dataWithContentsOfURL:url];
jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
postArray = [[NSMutableArray alloc] init];
for(int i = 0; i < jsonArray.count; i++)
{
NSString *nickname = [[jsonArray objectAtIndex:i] objectForKey:#"nickname"];
NSString *squeal = [[jsonArray objectAtIndex:i] objectForKey:#"squeal"];
[postArray addObject:[[Post alloc] initWithNickname:nickname andSqueal:squeal]];
}
viewArray = [[NSMutableArray alloc] init];
for(int i = 0; i < postArray.count; i++)
{
Post *postObject;
postObject = [postArray objectAtIndex:i];
UILabel *nicknameLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, 15, 320, 30)];
nicknameLabel.text = postObject.nickname;
nicknameLabel.font = [UIFont boldSystemFontOfSize:20];
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(25, 42, 320, 0)];
textView.font = [UIFont systemFontOfSize:15];
textView.text = postObject.squeal;
textView.editable = false;
[textView setScrollEnabled:false];
[textView sizeToFit];
[textView layoutIfNeeded];
UIView *view = [[UIView alloc] initWithFrame: CGRectMake (0, 0, 320, 30+textView.frame.size.height)];
[view addSubview:nicknameLabel];
[view addSubview:textView];
[viewArray addObject:view];
}
[self.tableView reloadData];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return postArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
[cell.contentView addSubview:[viewArray objectAtIndex:indexPath.row]];
}
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 0;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
UIView *view = [viewArray objectAtIndex:indexPath.row];
return view.frame.size.height+30;
}
#end
UITableView reuses the cells with the same reuse identifier, which means that when you scroll so that a row is scrolled out of the visible area, it will be used to show new rows. That's why when your 1st and 2nd rows were scrolled out of the view, they were used to show the 5th and 6th row.
You need to modify how you load cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
// Add and setup views here.
}
//Add content to view here
// e.g. cell.textLabel.text = #"Some text";
return cell;
}
BTW You can use the property textLabelof UITableViewCellinstead of creating a new label and adding it as as subview. If you need to have more control over your custom cell, then you should create a custom class and use a Storyboard file or a Xib file.
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
else
{
[[cell.contentView subviews] makeObjectsPerformSelector:#selector(removeFromSuperview)];
}
[cell.contentView addSubview:[viewArray objectAtIndex:indexPath.row]];
In your cellForRowAtIndexPath method, you are adding a subview to the cell's content view only if the cell is being initialized for the first time.
Rather, you should add/replace the subview on each call to cellForRowAtIndexPath.
I have one "+" button in UIView. My requirement is, if i click that button UITextFields displayed in UITableViewCells. I am having idea how to display the UITextFields in UIView if user clicks the "+" button. But i dont have any idea how to display UITextFields inside of UITableViewCells if user hits the "+" button. Please kindly help me anybody. Yesterday i strucked with this functionality. I tried some code. But it is not worked properly. But i had not found any solution. Thanks in advance.
UIButton *myGreenIconButton1 = [UIButton buttonWithType:UIButtonTypeCustom];
[myGreenIconButton1 addTarget:self action:#selector(GreenIconButtonClicked)forControlEvents:UIControlEventTouchUpInside];
[myGreenIconButton1 setBackgroundImage:[UIImage imageNamed:#"index.jpg"] forState:UIControlStateNormal];
myGreenIconButton1.backgroundColor = [UIColor clearColor];
myGreenIconButton1.frame = CGRectMake(285, 144, 25, 25);
[self.view addSubview:myGreenIconButton1];
-(void)GreenIconButtonClicked
{
view=[[UIView alloc]initWithFrame:CGRectMake(0, 80, 300, 20)];
text1=[[UITextField alloc]initWithFrame:CGRectMake(10, 80, 100, 20)];
text1.borderStyle=UITextBorderStyleRoundedRect;
text1.backgroundColor=[UIColor clearColor];
text1.backgroundColor=[UIColor colorWithRed:0.662745 green:0.662745 blue:0.662745 alpha:0.5];
text1.font=[UIFont systemFontOfSize:14.0];
text1.contentVerticalAlignment=UIControlContentVerticalAlignmentCenter;
text1.textAlignment=NSTextAlignmentCenter;
text1.delegate=self;
[view addSubview:text1];
text2=[[UITextField alloc]initWithFrame:CGRectMake(120, 80, 100, 20)];
text2.borderStyle=UITextBorderStyleRoundedRect;
text2.backgroundColor=[UIColor clearColor];
text2.backgroundColor=[UIColor colorWithRed:0.662745 green:0.662745 blue:0.662745 alpha:0.5];
text2.font=[UIFont systemFontOfSize:14.0];
text2.contentVerticalAlignment=UIControlContentVerticalAlignmentCenter;
text2.textAlignment=NSTextAlignmentCenter;
text2.delegate=self;
[view addSubview:text2];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
}
[cell.textLabel setText:#""];
[view setTag:101];
NSIndexPath *ip = [NSIndexPath indexPathForRow:0 inSection:0];
UITableViewCell *cell1 = [self.tableView cellForRowAtIndexPath:ip];
UITextField *textField = (UITextField*)[cell1 viewWithTag:101];
UITextField *textField1=(UITextField*)[cell1 viewWithTag:101];
UITextField *textField2=(UITextField*)[cell1 viewWithTag:101];
[cell.contentView addSubview:text1];
[cell.contentView addSubview:text2];
[cell.contentView addSubview:text3];
return cell;
}
I have created a example for your requirement and posted it on github. You can find code Here
I have created a custom table view cell with text field on it.
First create custom cell with xib or without and do following manner its working for you :
CustomCell.h
#import <UIKit/UIKit.h>
#interface CustomCell : UITableViewCell {
}
#property (strong,nonatomic) IBOutlet UITextField *textField;
#end
CustomCell.m
#import "CustomCell.h"
#implementation CustomCell
#synthesize textField;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
self.textField = [[UITextField alloc] init];
[self.contentView addSubview:self.textField];
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
Your TableView .h
#property (strong,nonatomic) NSMutableArray *array;
#property (strong, nonatomic) IBOutlet UITableView *tblView;
Your Table View .m
#synthesize array;
#synthesize tblView;
-(void)viewWillAppear:(BOOL)animated {
array = [[NSMutableArray alloc] init];
[tblView reloadData];
}
-(int)numberOfSectionsInTableView:(UITableView *)tableView
{
if( [array count ] > 0 )
{
return 1;
}
return 0;
}
-(int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if( [array count ] > 0 )
{
return [array Count];
}
return 0;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellIdentifier = [NSString stringWithFormat:#"CustomCell%d%d",indexPath.row,indexPath.section];
[tblCreateProfile registerNib:[UINib nibWithNibName:#"CustomCell" bundle:nil] forCellReuseIdentifier:cellIdentifier];
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
if(cell == nil)
{
cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
cellIdentifier =nil;
cell.textField.text = [array objectAtIndex:indexPath.row];
return cell;
}
-(void)GreenIconButtonClicked
{
[array addObject:#"Test"];
[tblView reloadData];
}
So just try in Custom TableViewCells. So that You can Achieve the solution for this problem.
I have searched, with no success, for an answer to this issue. I have created a UITableView using the Grouped style. It is a landscape app for the iPad and I only want the table on the left (in the area 0, 300, 20, 748), however setting the tableView.frame = CGRectMake(0, 20, 300, 748) does nothing.
#import "ViewController.h"
#interface ViewController ()
#property (strong, nonatomic) NSArray *sections;
#end
#implementation ViewController
#synthesize sections = _sections;
- (void)viewDidLoad
{
UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 20, 300, 748) style:UITableViewStyleGrouped];
tableView.frame = CGRectMake(0, 20, 300, 748);
tableView.delegate = self;
tableView.dataSource = self;
[tableView reloadData];
NSArray *first = [NSArray arrayWithObjects:#"first", #"second", #"third", nil];
NSArray *second = [NSArray arrayWithObjects:#"fourth", #"fifth", #"sixth", nil];
self.sections = [NSArray arrayWithObjects:first, second, nil];
self.view = tableView;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [self.sections count];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [[self.sections objectAtIndex:section] count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = #"MyReuseIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier];
}
cell.textLabel.text = [[self.sections objectAtIndex:[indexPath section]]objectAtIndex:[indexPath row]];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
tableView.frame = CGRectMake(0, 20, 300, 748);
return cell;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
I'm looking for a way to resize the table so that it is only 300 pixels wide and on the left. Any suggestions on how this is possible?
Assuming your ViewController is a UIViewController, instead of making the table view the main view (which will be resized for you), simply add the table view.
Replace:
self.view = tableView;
with:
[self.view addSubview:tableView];
Now the table view will keep the frame that you set.
Since you want the table view down the left side, and presumably to fill the height, you really should do this:
- (void)viewDidLoad {
UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 300, self.view.frame.size.height) style:UITableViewStyleGrouped];
tableView.delegate = self;
tableView.dataSource = self;
NSArray *first = [NSArray arrayWithObjects:#"first", #"second", #"third", nil];
NSArray *second = [NSArray arrayWithObjects:#"fourth", #"fifth", #"sixth", nil];
self.sections = [NSArray arrayWithObjects:first, second, nil];
tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
[self.view addSubview:tableView];
[tableView reloadData]; // don't reload until it's added and the data is ready
}
I am very new to Objective-C. I just searched and tried to learn about UITableView.
I have created this UITableView. instead of "a" in all the rows i want it to be in a sequence like "a b c d..." and if i increase the no of rows it should scroll. its not scrolling so here is my code.
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
CGRect frame = self.view.frame;
UITableView *tableView = [[UITableView alloc] initWithFrame:frame style:UITableViewStylePlain];
tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
tableView.backgroundColor = [UIColor cyanColor];
tableView.delegate = self;
tableView.dataSource = self;
[self.view addSubview:tableView];
[super viewDidLoad];
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 20;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cellIDent"];
cell.textLabel.text = #"a";
return cell;
}
#end
set table view Delegates in IB or if u created Programmatically then in viewDidLoad Take one array fill it Dynamically or Statically.Give array count in NumberOfRowsInsection method and reload table view at appropriate place
in your cellForRowAtIndexPath: add these lines
char ch = 'a' + indexPath.row;
cell.textLabel.text = [NSString stringWithFormat:#"%c" , ch];
Check this tutorial, I'm sure it will help you
UItableView Guide
and for scrolling, You don't need to do anything yourselves, as the number of cells increases beyond the provided size, it automatically becomes scrollable and make sure that scrolling is enabled in your UITableView attribute inspector, check the image
Happy Coding
Regards
Use below code.....define alphabetarr in globally then use it in code...
- (void)viewDidLoad
{
alphabetarr = [[NSArray alloc] initWithObjects:#"a",#"b",#"c",#"d",#"e",#"f",#"g",#"h",#"i",#"j",#"k",#"l",#"m",#"n",#"o",#"p",#"q",#"r",#"s",#"t",#"u",#"v",#"w",#"x",#"y",#"z", nil];
CGRect frame = self.view.frame;
UITableView *tableview = [[UITableView alloc] initWithFrame:frame];
tableview.backgroundColor = [UIColor cyanColor];
tableview.separatorColor = [UIColor blackColor];
tableview.delegate = self;
tableview.dataSource = self;
[self.view addSubview:tableview];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [alphabetarr count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 30.0 ;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell!=nil) {
cell = nil;
}
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
cell.textLabel.text = [alphabetarr objectAtIndex:indexPath.row];
return cell;
}