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
}
Related
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'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;
}
How do i get the value (the selected state) from my segmentedcontrols in the tableviewcells?
When i press the button "Get states" it should return the value for each of the segmented controls. I have tried different methods, but I can't find one that works :(
My code so far:
- (void)viewDidLoad
{
[super viewDidLoad];
tableData = [[NSMutableArray alloc] initWithCapacity:0];
tableData = [NSArray arrayWithObjects:#"First", #"Second", #"Third", nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [tableData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = nil;
cell = [tableView dequeueReusableCellWithIdentifier:#"StateCell"];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"StateCell"];
}
//Config cell..
cell.textLabel.text = [tableData objectAtIndex:indexPath.row];
NSArray *itemArray = [NSArray arrayWithObjects: #"1", #"2", #"3", nil];
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:itemArray];
segmentedControl.frame = CGRectMake(110, 7, 100, 28);
[cell.contentView addSubview:segmentedControl];
return cell;
[[self tableView] reloadData];
}
- (IBAction)getStates:(id)sender {
// Ruturn the current selected statement, for the individual cell's segmentedcontrol..
// Ex. First = SelectedState 1, Second = SelectedState 0 & Third = SelectedState 2..
}
So what I'm really is asking for; is what the "Get states" button action has to do..
Thanks for your time!
Your code has a couple of problems. Most of them happen because a UITableView reuses its cells.
You are creating a new UISegmentedControl each time a cell is displayed, which you should not. You should create the UISegmentedControl only if you create the cell, move that code into the cell == nil).
You don't have a dataSource that saves the state of the segments. You should not save states in views, especially not if you are dealing with a tableView, because cells are reused.
Here's an example that will get the functionality you need.
// this is an object of your model, it has a title and saves the selected index
#interface MBFancyObject : NSObject
#property (strong, nonatomic) NSString *title;
#property (assign, nonatomic) NSInteger selectedIndex;
#end
#implementation MBFancyObject
#end
#interface MasterViewController () {
NSMutableArray *_objects; // stores instances of MBFancyObject
}
#end
#implementation MasterViewController
- (void)viewDidLoad {
[super viewDidLoad];
// set up the model
_objects = [NSMutableArray array];
for (NSInteger i = 0; i < 6; i++) {
MBFancyObject *object = [[MBFancyObject alloc] init];
object.title = [NSString stringWithFormat:#"Object #%ld", (long)i];
object.selectedIndex = i % 3;
[_objects addObject:object];
}
UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithTitle:#"Get States" style:UIBarButtonItemStyleBordered target:self action:#selector(logStates:)];
self.navigationItem.rightBarButtonItem = button;
}
#pragma mark - Table View
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return _objects.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"FancyCell"];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"FancyCell"];
// add the segmentedControl when you create a new cell
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:#[#"1", #"2", #"3"]];
segmentedControl.frame = CGRectMake(110, 7, 100, 28);
[cell.contentView addSubview:segmentedControl];
// add an action so we can change our model if the view changes
[segmentedControl addTarget:self action:#selector(didChangeSegmentedControl:) forControlEvents:UIControlEventValueChanged];
// use a tag so we can retrieve the segmentedControl later
segmentedControl.tag = 42;
}
// either if the cell could be dequeued or you created a new cell,
// segmentedControl will contain a valid instance
UISegmentedControl *segmentedControl = (UISegmentedControl *)[cell.contentView viewWithTag:42];
MBFancyObject *object = _objects[indexPath.row];
cell.textLabel.text = object.title;
segmentedControl.selectedSegmentIndex = object.selectedIndex;
return cell;
}
- (IBAction)didChangeSegmentedControl:(UISegmentedControl *)sender {
// transform the origin of the cell to the frame of the tableView
CGPoint senderOriginInTableView = [self.tableView convertPoint:CGPointZero fromView:sender];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:senderOriginInTableView];
NSAssert(indexPath, #"must have a valid indexPath");
MBFancyObject *object = _objects[indexPath.row];
object.selectedIndex = sender.selectedSegmentIndex;
}
- (IBAction)logStates:(id)sender {
// query the model, not the view
for (NSInteger i = 0; i < [_objects count]; i++) {
MBFancyObject *object = _objects[i];
NSLog(#"Object \"%#\" - %ld", object.title, (long)object.selectedIndex);
// since you have only one section, each indexPath is 0,i
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
}
}
#end
Use an array to store all the segment control values, and when click one segment control then just change the value correspondingly.
You have serious problem with reusing here
Do not ever allocate a new UI element in tableView:cellForRowAtIndexPath: method unless it is in the if condition if (cell == nil)
Change What in Your tableView:cellForRowAtIndexPath: to be
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"StateCell"];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"StateCell"];
// Add the Segmented Control
NSArray *itemArray = [NSArray arrayWithObjects: #"1", #"2", #"3", nil];
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:itemArray];
segmentedControl.frame = CGRectMake(110, 7, 100, 28);
segmentedControl.tag = 1;
[cell addSubview:segmentedControl];
}
//Config cell..
cell.textLabel.text = [tableData objectAtIndex:indexPath.row];
// Get that Segmented Control
UISegmentedControl *segmentedControl = (UISegmentedControl *)[cell viewWithTag:1];
segmentedControl.selectedSegmentIndex = 0; // Set your default value here or add your data in an array and read from that array
return cell;
Then in the action of the button do that
for (UITableViewCell *cell in [tableView visibleCells]) {
UISegmentedControl *segmentedControl = (UISegmentedControl *)[cell viewWithTag:1];
NSLog(#"%d",segmentedControl.selectedSegmentIndex);
}
However this code is not perfect unless you have only 3 cells in your table to avoid reuse or visibility problem
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;
}
I have the code below to display popover with tableview and it works perfectly.
The tableview displays 13 numbers and I can scroll and see the same but when I release mouse-touch on simulator it goes back to the top.
It does not stay at the row which its displaying but takes me back to 1st to 10th row .
How do I make it stay in the position after scrolling. Or any fix in the below code.
Thanks in Advance.
- (IBAction)btn:(id)sender {
if([popoverController isPopoverVisible])
{
[popoverController dismissPopoverAnimated:YES];
return;
}
//build our custom popover view
UIViewController* popoverContent = [[UIViewController alloc]init];
UIView* popoverView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 680)];
popoverView.backgroundColor = [UIColor blackColor];
numbers = [[NSMutableArray alloc] initWithObjects:#"1",#"2", #"3",#"4",#"5", #"6",#"7", #"8", #"9",#"10",#"11", #"12",#"13",nil];
UITableView *tblViewMenu = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, 680)];
tblViewMenu.delegate = self;
tblViewMenu.dataSource = self;
tblViewMenu.rowHeight = 32;
[popoverView addSubview:tblViewMenu];
popoverContent.view = popoverView;
popoverContent.contentSizeForViewInPopover = CGSizeMake(320, 320);
popoverController = [[UIPopoverController alloc]
initWithContentViewController:popoverContent];
[popoverController presentPopoverFromRect:self.btn.frame inView:self.view permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return [numbers count];
}
// Customize the appearance of table view 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] ;
}
// Configure the cell...
NSString *color = [numbers objectAtIndex:indexPath.row];
cell.textLabel.text = color;
return cell;
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *number = [numbers objectAtIndex:indexPath.row];
NSLog(#"%#",number);
[popoverController dismissPopoverAnimated:YES];
}
I Guess I need to change the values below:
UIView* popoverView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 680)];
UITableView *tblViewMenu = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320,680)]];
If I use
UIView* popoverView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 320)];
Then
UITableView *tblViewMenu = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320,320)]];
But when I scroll down it keeps coming to the top row .It does not stay in the same row which is being scrolled to .
Use autoresizing correctly!
Popover - has content size
popoverView - its initial size should be the same as popover's content size and use
UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight
tblViewMenu- its initial size should be the same as the size of its ancestor (popoverView), again, use UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight
Your table is not scrolling because it is so big that it doesn't needs scrolling. Only the popover is clipping it.
CGSize contentSize = CGSizeMake(320, 320);
UIView* popoverView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, contentSize.width, contentSize.height)];
popoverView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
UITableView *tblViewMenu = [[UITableView alloc]initWithFrame:popoverView.bounds];
tblViewMenu.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
popoverContent.contentSizeForViewInPopover = contentSize;
Try set the ContentSize of the tableView, like this:
[tblViewMenu setContentSize:CGSizeMake(320,680)];
Also, I'd prefere to make the size of the tableView dynamic. depend on your tableView Datasource array.
UPDATE
To make the tableView dynamic, use this:
[tblViewMenu setContentSize:CGSizeMake(320, ([numbers count] * 32))];
And if you have a header view that has a hight like the other cells, just add 1 to [number count], that would be like this:
[tblViewMenu setContentSize:CGSizeMake(320, (([numbers count] + 1) * 32))];