I'm completely new to iPhone development. I have a query regarding how to implement scroll view in table view. I'm using following code
#import <UIKit/UIKit.h>
#class ScrollViewViewController;
#interface ScrollViewAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
ScrollViewViewController *viewController;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) IBOutlet ScrollViewViewController *viewController;
#end
////////////////////////////////////////////
#import "ScrollViewAppDelegate.h"
#import "ScrollViewViewController.h"
#implementation ScrollViewAppDelegate
#synthesize window;
#synthesize viewController;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Override point for customization after app launch
[window addSubview:viewController.view];
[window makeKeyAndVisible];
}
- (void)dealloc {
[viewController release];
[window release];
[super dealloc];
}
#end
///////////////////////////
#import <UIKit/UIKit.h>
#interface MyTableCell : UITableViewCell {
NSMutableArray *columns;
}
- (void)addColumn:(CGFloat)position;
#end
//////////////////////////
#import "MyTableCell.h"
#implementation MyTableCell
- (id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
if (self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) {
// Initialization code
columns = [NSMutableArray arrayWithCapacity:5];
[columns retain];
}
return self;
}
- (void)addColumn:(CGFloat)position {
[columns addObject:[NSNumber numberWithFloat:position]];
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void)drawRect:(CGRect)rect {
CGContextRef ctx = UIGraphicsGetCurrentContext();
// just match the color and size of the horizontal line
CGContextSetRGBStrokeColor(ctx, 0.5, 0.5, 0.5, 1.0);
CGContextSetLineWidth(ctx, 0.25);
for (int i = 0; i < [columns count]; i++) {
// get the position for the vertical line
CGFloat f = [((NSNumber*) [columns objectAtIndex:i]) floatValue];
CGContextMoveToPoint(ctx, f, 0);
CGContextAddLineToPoint(ctx, f, self.bounds.size.height);
}
CGContextStrokePath(ctx);
[super drawRect:rect];
}
- (void)dealloc {
[super dealloc];
[columns dealloc];
}
#end
//////////////////////
#import <UIKit/UIKit.h>
#interface RootViewController : UITableViewController {
}
#end
/////////////////
#import "RootViewController.h"
#import "MyTableCell.h"
#implementation RootViewController
#define LABEL_TAG 1
#define VALUE_TAG 2
#define FIRST_CELL_IDENTIFIER #"TrailItemCell"
#define SECOND_CELL_IDENTIFIER #"RegularCell"
- (void)viewDidLoad {
// Add the following line if you want the list to be editable
// self.navigationItem.leftBarButtonItem = self.editButtonItem;
self.title = #"Grids!";
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
return 19;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *MyIdentifier = [NSString stringWithFormat:#"MyIdentifier %i", indexPath.row];
MyTableCell *cell = (MyTableCell *)[tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[[MyTableCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(0.0, 0, 30.0,
tableView.rowHeight)] autorelease];
[cell addColumn:40];
label.tag = LABEL_TAG;
label.font = [UIFont systemFontOfSize:12.0];
label.text =#"S.NO";// [NSString stringWithFormat:#"%d", indexPath.row];
label.textAlignment = UITextAlignmentRight;
label.textColor = [UIColor redColor];
label.autoresizingMask = UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:label];
label = [[[UILabel alloc] initWithFrame:CGRectMake(40.0, 0, 70.0,
tableView.rowHeight)] autorelease];
[cell addColumn:120];
label.tag = VALUE_TAG;
label.font = [UIFont systemFontOfSize:12.0];
// add some silly value
label.text =#"Product ID";// [NSString stringWithFormat:#"%d", indexPath.row * 4];
label.textAlignment = UITextAlignmentRight;
label.textColor = [UIColor blueColor];
label.autoresizingMask = UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:label];
label = [[[UILabel alloc] initWithFrame:CGRectMake(134.0, 0, 70.0,
tableView.rowHeight)] autorelease];
[cell addColumn:220];
label.tag = VALUE_TAG;
label.font = [UIFont systemFontOfSize:12.0];
// add some silly value
label.text =#"Product Name";// [NSString stringWithFormat:#"%d", indexPath.row * 4];
label.textAlignment = UITextAlignmentRight;
label.textColor = [UIColor greenColor];
label.autoresizingMask = UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:label];
label = [[[UILabel alloc] initWithFrame:CGRectMake(230.0, 0, 70.0,
tableView.rowHeight)] autorelease];
[cell addColumn:310];
label.tag = VALUE_TAG;
label.font = [UIFont systemFontOfSize:12.0];
// add some silly value
label.text =#"Customer Name";// [NSString stringWithFormat:#"%d", indexPath.row * 4];
label.textAlignment = UITextAlignmentRight;
label.textColor = [UIColor greenColor];
label.autoresizingMask = UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:label];
label = [[[UILabel alloc] initWithFrame:CGRectMake(320.0, 0, 70.0,
tableView.rowHeight)] autorelease];
[cell addColumn:400];
label.tag = VALUE_TAG;
label.font = [UIFont systemFontOfSize:12.0];
// add some silly value
label.text =#"Customer Product";// [NSString stringWithFormat:#"%d", indexPath.row * 4];
label.textAlignment = UITextAlignmentRight;
label.textColor = [UIColor greenColor];
label.autoresizingMask = UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:label];
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated {
}
- (void)viewDidDisappear:(BOOL)animated {
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
// Release anything that's not essential, such as cached data
}
- (void)dealloc {
[super dealloc];
}
#end
////////////
#import <UIKit/UIKit.h>
#interface ScrollViewViewController : UIViewController<UIScrollViewDelegate> {
}
#end
/////////////
#import "ScrollViewViewController.h"
#import "RootViewController.h"
#implementation ScrollViewViewController
/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
// Custom initialization
}
return self;
}
*/
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
RootViewController *RootViewControllerLink = [[RootViewController alloc]initWithNibName:#"RootViewController" bundle:nil];
RootViewControllerLink.view.tag = 100;
/* UIImageView *imgView = [[[UIImageView alloc] initWithImage:
[UIImage imageNamed:#"winkler-gnu-blue.png"]] autorelease];
imgView.tag = 100;
*/
UIScrollView *scrollView = [[[UIScrollView alloc]
initWithFrame:CGRectMake(0,0,320,480)] autorelease];
scrollView.delegate = self;
scrollView.minimumZoomScale = 0.25;
scrollView.maximumZoomScale = 2;
scrollView.bounces = NO;
scrollView.showsHorizontalScrollIndicator = NO;
scrollView.showsVerticalScrollIndicator = NO;
scrollView.contentSize = RootViewControllerLink.view.frame.size;
scrollView.contentOffset =
CGPointMake((RootViewControllerLink.view.frame.size.width-320)/2,
(RootViewControllerLink.view.frame.size.height-480)/2);
[scrollView addSubview:RootViewControllerLink.view];
self.view = scrollView;
}
/*- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
return [self.view viewWithTag:100];
}
- (BOOL)touchesShouldBegin:(NSSet *)touches withEvent:(UIEvent *)event inContentView:(UIView *)view
{
return YES;
}// default returns YES
- (BOOL)touchesShouldCancelInContentView:(UIView *)view
{
return YES;
}
*/
// not called if canCancelContentTouches is NO. default returns YES if view isn't UIControl
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
#end
In above code if I set scroll for UIIMage then it works but if I set scroll view for RootViewController then it doesn't work.
I didn't read your code, please reformat it so others can read it easily.
What do you mean by a UIScrollView in an UITableView? Inside the cells? Still I don't get it.
FYI UITableView inherits from UIScrollView ...
What functionality do you exactly want to achieve?
I will recommend to read some of the samples given by Apple. There are very good and extensive examples specially regarding UIKit.
Related
I have a collections view and the view works fine when I load the data initially, but crashes when I try to reload it. take a look at the reload thats happening on the method - scrollViewDidEndDecelerating
and the error is
-[FeedCollectionViewCell release]: message sent to deallocated instance 0x800d6f70
here is the code.
This the Controller:
#interface MyViewController : UIViewController <UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout, UIScrollViewDelegate>
{
}
#property (retain, nonatomic) IBOutlet UICollectionView *collectionView;
#end
This is the implementation :
#implementation MyViewController
#interface FeedCollectionViewController ()
#property (nonatomic, strong) NSMutableArray *dataArray;
-(void)getData;
#end
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
if (self.dataArray == nil) {
self.dataArray = [[NSMutableArray alloc] init];
}
}
return self;
}
- (void)viewDidLoad
{
[self.collectionView registerClass:[FeedCollectionViewCell class] forCellWithReuseIdentifier:[FeedCollectionViewCell reuseIdentifier]];
// Configure layout
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
[flowLayout setItemSize:CGSizeMake(153, 128)];
[flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
[self.collectionView setCollectionViewLayout:flowLayout];
[self getData];
}
-(void)getData
{
// here I make a call to the server to get the data and I set the data array
self.dataArray = mydatafromserver
[self.collectionView reloadData];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath;
{
FeedCollectionViewCell *cell = (FeedCollectionViewCell *)[cv dequeueReusableCellWithReuseIdentifier:[FeedCollectionViewCell reuseIdentifier] forIndexPath:indexPath];
[cell.label setText:[[self.dataArray objectAtIndex:indexPath.row] name];
return cell;
}
- (void)scrollViewDidEndDecelerating:(UICollectionView *) collectionView
{
NSLog(#"FeedCollectionViewController::scrollViewDidEndDecelerating");
CGPoint offset = collectionView.contentOffset;
CGRect bounds = collectionView.bounds;
CGSize size = collectionView.contentSize;
UIEdgeInsets inset = collectionView.contentInset;
float y = offset.y + bounds.size.height - inset.bottom;
float h = size.height;
// NSLog(#"offset: %f", offset.y);
// NSLog(#"content.height: %f", size.height);
// NSLog(#"bounds.height: %f", bounds.size.height);
// NSLog(#"inset.top: %f", inset.top);
// NSLog(#"inset.bottom: %f", inset.bottom);
// NSLog(#"pos: %f of %f", y, h);
float reload_distance = 300;
if(y > h - reload_distance) {
NSLog(#"load more rows...");
***//// FAIL HERE***
[self.collectionView reloadData];
}
}
Here is the cell
#import <UIKit/UIKit.h>
#define FB_COLL_CELL_IDENTIFIER #"CollectionCellIdentifier"
#interface FeedCollectionViewCell : UICollectionViewCell
#property (retain, nonatomic) IBOutlet UIImageView *image;
#property (retain, nonatomic) IBOutlet UILabel *label;
#property (retain, nonatomic) IBOutlet UIActivityIndicatorView *spinner;
+ (NSString *)reuseIdentifier;
#end
#import "FeedCollectionViewCell.h"
#import "CustomCellBackground.h"
#implementation FeedCollectionViewCell
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
NSLog(#"FeedCollectionViewCell initWithFrame");
// Initialization code
NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:#"FeedCollectionViewCell" owner:self options:nil];
if ([arrayOfViews count] < 1) {
return nil;
}
if (![[arrayOfViews objectAtIndex:0] isKindOfClass:[UICollectionViewCell class]]) {
return nil;
}
self = [arrayOfViews objectAtIndex:0];
CustomCellBackground *backgroundView = [[CustomCellBackground alloc] initWithFrame:CGRectZero];
self.selectedBackgroundView = backgroundView;
}
return self;
}
+ (NSString *)reuseIdentifier
{
NSLog(#"FBDisplayCell ... static reuseIdentifier called ");
return (NSString *)FB_COLL_CELL_IDENTIFIER;
}
#end
and this is another one. adding this because its being used. I dont think the problem is here, but u never know!
#import <UIKit/UIKit.h>
#interface CustomCellBackground : UIView
#end
#import "CustomCellBackground.h"
#implementation CustomCellBackground
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
- (void)drawRect:(CGRect)rect
{
// draw a rounded rect bezier path filled with blue
CGContextRef aRef = UIGraphicsGetCurrentContext();
CGContextSaveGState(aRef);
UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:5.0f];
[bezierPath setLineWidth:5.0f];
[[UIColor blackColor] setStroke];
UIColor *fillColor = [UIColor colorWithRed:0.529 green:0.808 blue:0.922 alpha:1]; // color equivalent is #87ceeb
[fillColor setFill];
[bezierPath stroke];
[bezierPath fill];
CGContextRestoreGState(aRef);
}
#end
The issue was with the UICollectioViewCell -initWithFrame
i changed to not load the nib and i started creating my own
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor colorWithWhite:0.85f alpha:1.0f];
self.layer.borderColor = [UIColor whiteColor].CGColor;
self.layer.borderWidth = 3.0f;
self.layer.shadowColor = [UIColor blackColor].CGColor;
self.layer.shadowRadius = 3.0f;
self.layer.shadowOffset = CGSizeMake(0.0f, 2.0f);
self.layer.shadowOpacity = 0.5f;
self.imageView = [[UIImageView alloc] initWithFrame:self.bounds];
self.imageView.contentMode = UIViewContentModeScaleAspectFill;
self.imageView.clipsToBounds = YES;
[self.contentView addSubview:self.imageView];
}
return self;
}
I have inherited some old iOS code and have attempted to integrate it into a new iOS 6 application. I have implemented most of the code and so far everything has worked. I'm now working on the last bit of that old code. I'm implementing a set of views to show a rss for a news section of my app. I've implemented the categories view, which upon selecting an item would display the individual items within that category. However nothing gets displayed. I've made all the modifications that I'm aware of that I needed to do, however I'm no expert at iOS development and am in need of some guidance. Below is a snapshot of the simulator as it's attempting to display the view, and below that is a copy of my .h and .m files. I don't know what is preventing anything in the table from showing up. And preemptive thanks to any help!
here's the snapshot of the simulator
Here is a snapshot of the storyboard showing the linking to the Table View
Here's the .h file
#import <UIKit/UIKit.h>
#import "BlogRssParser.h"
#class BlogRssParser;
#class BlogRssParserDelegate;
#class BlogRss;
#class XMLCategory;
#interface NewsViewController : UIViewController <UITableViewDataSource,UITableViewDelegate, BlogRssParserDelegate> {
BlogRssParser * _rssParser;
XMLCategory * _currItem;
}
#property (nonatomic, retain) BlogRssParser * rssParser;
#property (readwrite, retain) XMLCategory * currItem;
#property (nonatomic, retain) IBOutlet UITableView *itemTableView;
#end
Here is my .m file
#import "NewsViewController.h"
#import "NewsDetailsViewController.h"
#import "BlogRssParser.h"
#import "BlogRss.h"
#import "XMLCategory.h"
#define kLabelTag 1;
#interface NewsViewController ()
#end
#implementation NewsViewController
#synthesize rssParser = _rssParser;
#synthesize currItem = _currItem;
- (void)navBarInit {
UIBarButtonItem *refreshBarButton = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
target:self action:#selector(reloadRss)];
[self.navigationItem setRightBarButtonItem:refreshBarButton animated:YES];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.itemTableView.delegate = self;
self.itemTableView.dataSource = self;
- (void) viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[self navBarInit];
[self.itemTableView reloadData];
self.itemTableView.userInteractionEnabled = NO;
}
- (void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
_rssParser = [[BlogRssParser alloc]init];
_rssParser.delegate = self;
[[self rssParser]startProcess:[_currItem categoryId]];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)reloadRss{
[[self rssParser]startProcess:[_currItem categoryId]];
[[self itemTableView]reloadData];
}
- (void)processCompleted{
[[self itemTableView]reloadData];
// _tableView.userInteractionEnabled = YES;
[[self itemTableView]setUserInteractionEnabled:YES];
}
-(void)processHasErrors{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"My Title" message:#"Unable to retrieve the news. Please check if you are connected to the internet."
delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [[[self rssParser]rssItems]count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
const CGFloat LABEL_TITLE_HEIGHT = 70.0;
const CGFloat LABEL_WIDTH = 210.0;
NSString * mediaUrl = [[[[self rssParser]rssItems]objectAtIndex:indexPath.row]mediaUrl];
NSData * imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:mediaUrl]];
UIImage * imageFromImageData;
if (imageData == nil) {
imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:#"http://www.urlForImage.image.png"]];
}
imageFromImageData = [[UIImage alloc] initWithData:imageData];
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:#"rssItemCell"];
if(nil == cell){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"rssItemCell"];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
UILabel * _topLabel =
[[UILabel alloc]
initWithFrame:
CGRectMake(
imageFromImageData.size.width + 10.0,
0.0,
LABEL_WIDTH,
LABEL_TITLE_HEIGHT)];
_topLabel.tag = kLabelTag;
_topLabel.opaque = NO;
_topLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin;
_topLabel.backgroundColor = [UIColor clearColor];
_topLabel.textColor = [UIColor colorWithRed:0.25 green:0.0 blue:0.0 alpha:1.0];
_topLabel.highlightedTextColor = [UIColor colorWithRed:1.0 green:1.0 blue:0.9 alpha:1.0];
_topLabel.font = [UIFont systemFontOfSize:[UIFont labelFontSize]];
_topLabel.numberOfLines = 0;
[cell.contentView addSubview:_topLabel];
}
cell.imageView.image = imageFromImageData;
UILabel * topLabel = (UILabel *)[cell.contentView viewWithTag:1];
topLabel.text = [[[[self rssParser]rssItems]objectAtIndex:indexPath.row]title];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NewsDetailsViewController *tlc = [[DetailsViewController alloc]init];
tlc.currentItem = [[[self rssParser]rssItems]objectAtIndex:indexPath.row];
tlc.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController:tlc animated:YES completion:nil];
}
#end
I could not get a conclusion about the problem you are facing.
But here are few things you should check.
Because i cannot see even an empty table view in your screenshot
Do you have the TableView on the Nib file ?
It is mapped from The Nib file to the IBOutlet itemTableView ?
Add at least one table view cell (Drag and drop one prototype cell)..
like this
Then select that cell and give some name in "Reuse Identifier" with this identifier allow datasource..
First thing I would do is make sure that [[[self rssParser] rssItems] count] is actually returning > 0. Also, is this a copy&paste of your .m file? viewDidLoad is missing the closing brace, but Xcode would catch that.
The default scroll setting for a UIPickerView is set to vertical. Is it possible to implement a UIPickerView horizontally?
If so, could you please show me a sample or direct me where to helpful documentation?
you can use CPPickerView .. A custom, configurable, horizontal version of UIPickerView (based on the spinning-wheel or slot-machine metaphor), with an included table cell implementation. Originally intended for condensing the space/rows needed for a multi-option setting.
IN .h File
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController <UIPickerViewDelegate> {
IBOutlet UIPickerView *pickerView;
NSMutableArray *itemArray;
IBOutlet UILabel *myLabel;
}
#property (nonatomic, retain) UIPickerView *pickerView;
#property (nonatomic, retain) UILabel *myLabel;
#end
IN .XIB File
drag and drop UIPickerView And One UILable
Also connect BOTH the “delegate” and “Referencing Outlet” to the FileOwner.
IN .M File
#import "ViewController.h"
#implementation ViewController
#synthesize pickerView, myLabel;
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.pickerView.delegate = self;
self.pickerView.showsSelectionIndicator =YES;
self.pickerView.backgroundColor = [UIColor blackColor];
CGAffineTransform rotate = CGAffineTransformMakeRotation(M_PI_2);
rotate = CGAffineTransformScale(rotate, 0.1, 0.8);
[self.pickerView setTransform:rotate];
self.pickerView.center = CGPointMake(160,75);
UILabel *theview[20];
CGAffineTransform rotateItem = CGAffineTransformMakeRotation(-M_PI_2);
rotateItem = CGAffineTransformScale(rotateItem, 1, 10);
for (int i=0;i<20;i++) {
theview[i] = [[UILabel alloc] init];
theview[i].text = [NSString stringWithFormat:#"%d",i];
theview[i].textColor = [UIColor blackColor];
theview[i].frame = CGRectMake(0,0, 100, 100);
theview[i].backgroundColor = [UIColor clearColor];
theview[i].textAlignment = NSTextAlignmentCenter; //UITextAlignmentCenter is deprecated.
theview[i].shadowColor = [UIColor whiteColor];
theview[i].shadowOffset = CGSizeMake(-1,-1);
theview[i].adjustsFontSizeToFitWidth = YES;
UIFont *myFont = [UIFont fontWithName:#"Georgia" size:15];
[theview[i] setFont:myFont];
theview[i].transform = rotateItem;
}
itemArray = [[NSMutableArray alloc] init];
for (int j=0;j<20;j++) {
[itemArray addObject:theview[j]];
}
}
#pragma mark -
#pragma mark Picker View Methods
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView {
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component {
return [itemArray count];
}
- (UIView *)pickerView:(UIPickerView *)thePickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
return [itemArray objectAtIndex:row];
}
- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
myLabel.text = [NSString stringWithFormat:#"SELECTED: %d", row+1];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
#end
Here is the idea:
The scroll view has several sub views, in this example, A, B, C:
[A][B][C]
Once the user scrolls to C, the view can't scroll anymore, but I want to loop back to A, like this:
[C][A][B]
When the user keeps scrolling to the right, the view keeps filling previous views in at the end. When the user
scrolls to left the view should also have similar behavior,
in order to make the user think that this view is infinitely long:
[A][B][C][A][B][C][A][B][C][A][B][C][A][B][C][A][B][C].....
How can I implement this in actual code? Thank you.
you need to set a delegate method that gets called when the view is scrolled, and then check any view that is more than one screens worth of pixels away from being visible, if it is then reposition the view 3*screen width to the other side.
This is what you want( on iphone 7 plus). This is pure code UI, no storyboard.First you need add sub code in your AppDelegate.m.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
[self.window makeKeyAndVisible];
ViewController *vc = [ViewController alloc];
self.window.rootViewController = vc;
self.window.backgroundColor = [UIColor redColor];
return YES;
}
Second add sub code in ViewController.m
#interface ViewController ()<UIScrollViewDelegate>
#property (nonatomic, strong) UIScrollView *readCannelScrollView;
#property (nonatomic, strong) UIImageView *pageOneView;
#property (nonatomic, strong) UIImageView *pageTwoView;
#property (nonatomic, strong) UIImageView *pageThreeView;
#end
#implementation ViewController
- (void)dealloc
{
_readCannelScrollView = nil;
_pageOneView = nil;
_pageTwoView = nil;
_pageThreeView = nil;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
//容器的属性设置
self.readCannelScrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:self.readCannelScrollView];
CGSize size = self.readCannelScrollView.contentSize;
size.width = 414*3;
self.readCannelScrollView.contentSize = size;
self.readCannelScrollView.pagingEnabled = YES;
self.readCannelScrollView.showsHorizontalScrollIndicator = NO;
self.readCannelScrollView.delegate = self;
self.readCannelScrollView.contentOffset = CGPointMake(0, 0);
//end
//添加页面1
self.pageOneView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 414, self.view.bounds.size.height)];
self.pageOneView.backgroundColor = [UIColor lightGrayColor];
self.pageOneView.image = [UIImage imageNamed:#"1"];
// self.pageOneView.font = [UIFont systemFontOfSize:80];
// self.pageOneView.textAlignment = NSTextAlignmentCenter;
[self.readCannelScrollView addSubview:self.pageOneView];
//添加页面2
self.pageTwoView = [[UIImageView alloc] initWithFrame:CGRectMake(828, 0, 414, self.view.bounds.size.height)];
self.pageTwoView.backgroundColor = [UIColor greenColor];
self.pageTwoView.image = [UIImage imageNamed:#"2"];
// self.pageTwoView.font = [UIFont systemFontOfSize:80];
// self.pageTwoView.textAlignment = NSTextAlignmentCenter;
[self.readCannelScrollView addSubview:self.pageTwoView];
//添加页面3
self.pageThreeView = [[UIImageView alloc] initWithFrame:CGRectMake(828, 0, 414, self.view.bounds.size.height)];
self.pageThreeView.backgroundColor = [UIColor grayColor];
self.pageThreeView.image = [UIImage imageNamed:#"3"];
// self.pageThreeView.font = [UIFont systemFontOfSize:80];
// self.pageThreeView.textAlignment = NSTextAlignmentCenter;
[self.readCannelScrollView addSubview:self.pageThreeView];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark -
#pragma mark - scroll delegate
- (void) scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
NSLog(#"scrollView.contentOffset.x=%f",scrollView.contentOffset.x);
CGFloat pageWidth = scrollView.frame.size.width;
int currentPage = floor((scrollView.contentOffset.x-pageWidth/2)/pageWidth)+1;
if (currentPage == 0)
{
UIImageView *tmpTxtView = self.pageThreeView;
self.pageThreeView = self.pageTwoView;
self.pageTwoView = self.pageOneView;
self.pageOneView = tmpTxtView;
}
if (currentPage == 2)
{
//换指针
UIImageView *tmpTxtView = self.pageOneView;
self.pageOneView = self.pageTwoView;
self.pageTwoView = self.pageThreeView;
self.pageThreeView = tmpTxtView;
}
//恢复原位
self.pageOneView.frame = (CGRect){0,0,self.pageOneView.frame.size};
self.pageTwoView.frame = (CGRect){414,0,self.pageTwoView.frame.size};
self.pageThreeView.frame = (CGRect){828,0,self.pageThreeView.frame.size};
self.readCannelScrollView.contentOffset = CGPointMake(414, 0);
}
#end
If you are satisfied with my answer give me a star.I need reputation.
I am creating custom UITableViewCell before starting to create it i read many articles about it and I start to create my own CustomTableViewCell.
In my custom TableViewCell I have 4 filds:
UILabel* cellTitle
UILabel* cellDateTime
UIView* cellMainImage
UIImageView* arraow image
Here is how is my TableViewCell appear:
And here is the code: of CustomTableViewCell.h
#import <UIKit/UIKit.h>
#define TAGS_TITLE_SIZE 20.0f
#define TITLE_LABEL_TAG 1
#define DATA_TIME_LABEL_TAG 5
#define ARROW_IMAGE_TAG 6
#define MAIN_IMAGE_TAG 7
// Enumeration for initiakization TableView Cells
typedef enum {
NONE_TABLE_CELL = 0,
NEWS_FEED_TABLE_CELL = 1,
TAGS_TABLE_CELL = 2
}TableTypeEnumeration;
// Class for Custom Table View Cell.
#interface CustomTableViewCell : UITableViewCell {
// Title of the cell.
UILabel* cellTitle;
UILabel* cellDataTime;
UIView* cellMainImage;
UIImageView* cellArrowImage;
}
// Set the title of the cell.
- (void) SetCellTitle: (NSString*) _cellTitle;
- (void) SetCellDateTime: (NSString*) _cellDataTime;
- (void) ReleaseCellMainImage;
- (void) InitCellTitleLable;
- (void) InitCellDateTimeLabel;
- (void) InitCellMainImage;
// Init With Style (With additional parametr TableTypeEnumeration)
- (id)initWithStyle: (UITableViewCellStyle)style reuseIdentifier: (NSString *)reuseIdentifier tableType:(TableTypeEnumeration)tabletypeEnum;
#end
And here is the code of: CustomTableViewCell.m
#import "CustomTableViewCell.h"
#implementation CustomTableViewCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
return [self initWithStyle:style reuseIdentifier:reuseIdentifier tableType:NONE_TABLE_CELL];
}
- (id)initWithStyle: (UITableViewCellStyle)style reuseIdentifier: (NSString *)reuseIdentifier tableType:(TableTypeEnumeration)tabletypeEnum {
// Get Self.
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Switch table View Cells
switch(tabletypeEnum) {
case NEWS_FEED_TABLE_CELL: {
// Create Cell Title Text
cellTitle = [[UILabel alloc] initWithFrame:CGRectMake(75.0f, 2.5f, 180.0f, 33.0f)];
cellTitle.tag = TITLE_LABEL_TAG;
cellTitle.font = [UIFont boldSystemFontOfSize: 13.0f];
cellTitle.lineBreakMode = UILineBreakModeWordWrap;
cellTitle.numberOfLines = 0;
cellTitle.textAlignment = UITextAlignmentLeft;
cellTitle.textColor = [UIColor blackColor];
[self.contentView addSubview:cellTitle];
[cellTitle release];
// Create Cell Description Text.
cellDataTime = [[UILabel alloc] initWithFrame:CGRectMake(135.0f, 38.0f, 100.0f, 15.0f)];
cellDataTime.tag = DATA_TIME_LABEL_TAG;
cellDataTime.font = [UIFont italicSystemFontOfSize: 12.0f];
cellDataTime.textAlignment = UITextAlignmentLeft;
cellDataTime.textColor = [UIColor blackColor];
cellDataTime.lineBreakMode = UILineBreakModeWordWrap;
[self.contentView addSubview:cellDataTime];
[cellDataTime release];
// Create Cell Arrow Image.
cellArrowImage = [[UIImageView alloc] initWithFrame:CGRectMake(260.0f, 7.0f, 40.0f, 49.0f)];
cellArrowImage.tag = ARROW_IMAGE_TAG;
cellArrowImage.backgroundColor = [UIColor whiteColor];
cellArrowImage.image = [UIImage imageNamed:#"Grey Arrow.png"];;
[self.contentView addSubview:cellArrowImage];
[cellArrowImage release];
// Create Cell Main Image.
cellMainImage = [[[UIView alloc] initWithFrame:CGRectMake(2.0f, 2.5f, 55.0f, 50.0f)] autorelease];
cellMainImage.tag = MAIN_IMAGE_TAG;
[self.contentView addSubview:cellMainImage];
break;
}
case TAGS_TABLE_CELL: {
// Create and initialize Title of Custom Cell.
cellTitle = [[UILabel alloc] initWithFrame:CGRectMake(10, (44 - TAGS_TITLE_SIZE)/2, 260, 21)];
cellTitle.backgroundColor = [UIColor clearColor];
cellTitle.opaque = NO;
cellTitle.textColor = [UIColor blackColor];
cellTitle.highlightedTextColor = [UIColor whiteColor];
cellTitle.font = [UIFont boldSystemFontOfSize:TAGS_TITLE_SIZE];
cellTitle.textAlignment = UITextAlignmentLeft;
[self.contentView addSubview:cellTitle];
[cellTitle release];
break;
}
default: break;
}
}
return self;
}
- (void) ReleaseCellMainImage {
[cellMainImage release];
}
- (void) InitCellTitleLable {
cellTitle = (UILabel *)[self.contentView viewWithTag:TITLE_LABEL_TAG];
}
- (void) InitCellDateTimeLabel {
cellDataTime = (UILabel *)[self.contentView viewWithTag:DATA_TIME_LABEL_TAG];
}
- (void) InitCellMainImage {
//UIView* oldImage = [self.contentView viewWithTag:MAIN_IMAGE_TAG];
//[oldImage removeFromSuperview];
}
- (void) SetCellTitle: (NSString*) _cellTitle {
cellTitle.text = _cellTitle;
}
- (void) SetCellDateTime: (NSString*) _cellDataTime {
cellDataTime.text = _cellDataTime;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
}
- (void)dealloc {
// Call base delloc
[super dealloc];
}
#end
Now when I use my CustomTableViewCell in the code of the program the memory of my iphone always go up !!! Every time when I open tableView the memory grows for 2mb and when I open and close tableView for 10times it become more then 30mb !!! Whot can I do ???
And one more question
How I can get the event when user for example press on my image in custom cell ???
In addition to considering cell reuse as others say, if the memory use goes up with each open, you may have a memory leak. Perhaps the view you have that creates the table is not releasing it when deallocated.
You aren't reusing your cells. Hence a new cell is created everytime you scroll.
In your delegate you need to recreate cell as follows:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (nil == cell) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier] autorelease];
}
return cell;
Are you implementing cell re-use when creating the cell? There is no indication in the code that you attempt to dequeue a reusable cell from UITableView prior to the init, though this may be in the table view itself. As can be seen in Praveens post, there is an attempt to dequeue a cell, and only if this returns nil is the cell being initialised.
As a result, you may be creating a new cell object every time this particular cell comes into view. Is cell reuse adopted in the table view?
What code is in the tableview delegate method - tableView:cellForRowAtIndexPath?