How to render UITableViewCell - iphone

I create UITabBar template. Then I add to firstViewController a tableView. Make connections (UITableViewDataSource and UITableViewDelegate).
In didselect method I need to render selected UITableViewCell and animate it to one of UITabBars.
If I render UITableViewCell row = 0 - it's ok, But if I render UITableViewCell row > 0 (1,2,...) I get black rectangle.
I can render UITableViewCell contentView, but it will render without background.
How can I get snapshot of UITableViewCell with a background?
#import <UIKit/UIKit.h>
#interface AppDelegate : UIResponder <UIApplicationDelegate, UITabBarControllerDelegate>
#property (strong, nonatomic) UIWindow *window;
#property (strong, nonatomic) UITabBarController *tabBarController;
#end
#import "AppDelegate.h"
#import "FirstViewController.h"
#import "SecondViewController.h"
#implementation AppDelegate
#synthesize window = _window;
#synthesize tabBarController = _tabBarController;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions: (NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
UIViewController *viewController1 = [[FirstViewController alloc] initWithNibName:#"FirstViewController" bundle:nil];
UIViewController *viewController2 = [[SecondViewController alloc] initWithNibName:#"SecondViewController" bundle:nil];
self.tabBarController = [[UITabBarController alloc] init];
self.tabBarController.viewControllers = [NSArray arrayWithObjects:viewController1, viewController2, nil];
self.window.rootViewController = self.tabBarController;
[self.window makeKeyAndVisible];
return YES;
}
#import <UIKit/UIKit.h>
#interface FirstViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
#property (nonatomic, strong) IBOutlet UITableView *tableViewAnimation;
#property (nonatomic, retain) UIImageView *thumbnail;
- (UIImage*)screenshotFromView:(UIView *)view;
#end
#import "FirstViewController.h"
#import <QuartzCore/QuartzCore.h>
#implementation FirstViewController
#synthesize tableViewAnimation = _tableViewAnimation;
#synthesize thumbnail = _thumbnail;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(#"First", #"First");
self.tabBarItem.image = [UIImage imageNamed:#"first"];
}
return self;
}
#pragma mark - UITableView DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSUInteger count = 10;
return count;
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *goodsListCellIdentifier = #"ListOfGoodsIndetifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:goodsListCellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:goodsListCellIdentifier];
cell.textLabel.backgroundColor = [UIColor clearColor];
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.textLabel.text = #"detalied view";
return cell;
}
#pragma mark - UITableView Delegate
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
cell.backgroundColor = [UIColor redColor];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [_tableViewAnimation cellForRowAtIndexPath:indexPath];
CGRect imageViewFrame = cell.frame;
imageViewFrame.origin.y = 64.0 + tableView.frame.origin.y + imageViewFrame.origin.y - tableView.contentOffset.y;
// imageViewFrame.size.width = cell.contentView.frame.size.width;
UIImageView *imageView = [[UIImageView alloc] initWithFrame:imageViewFrame];
imageView.image = [self screenshotFromView:cell];
[self.tabBarController.view addSubview:imageView];
self.thumbnail = imageView;
self.thumbnail.hidden = NO;
self.view.userInteractionEnabled = NO;
[UIView animateWithDuration:1.0
animations:^{
CGRect tabBarFrame = self.tabBarController.tabBar.frame;
CGFloat xoffset = tabBarFrame.size.width / 2;
[_thumbnail setCenter:CGPointMake(xoffset * 0.5, tabBarFrame.origin.y + 25.0)];
[_thumbnail setTransform:CGAffineTransformMakeScale(0.1, 0.1)];
[_thumbnail setAlpha:0.4];
}
completion:^(BOOL finished){
[self.thumbnail removeFromSuperview];
self.thumbnail = nil;
self.view.userInteractionEnabled = YES;
}];
}
- (UIImage*)screenshotFromView:(UIView *)view {
// Create a graphics context with the target size
// On iOS 4 and later, use UIGraphicsBeginImageContextWithOptions to take the scale into consideration
// On iOS prior to 4, fall back to use UIGraphicsBeginImageContext
CGSize imageSize = view.bounds.size;
UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
// -renderInContext: renders in the coordinate space of the layer,
// so we must first apply the layer's geometry to the graphics context
CGContextSaveGState(context);
// Center the context around the window's anchor point
CGContextTranslateCTM(context, [view center].x, [view center].y);
// Apply the window's transform about the anchor point
CGContextConcatCTM(context, [view transform]);
// Offset by the portion of the bounds left of and above the anchor point
CGContextTranslateCTM(context, -[view bounds].size.width * [[view layer] anchorPoint].x, -[view bounds].size.height * [[view layer] anchorPoint].y);
// Render the layer hierarchy to the current context
[[view layer] renderInContext:context];
// Restore the context
CGContextRestoreGState(context);
// Retrieve the screenshot image
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
#end

The background is probably not rendered automatically by the cell but by the table instead.
Note that background is rendered depending on cell state (background / selected background).
You can take cell.backgroundView and render it before you render the cell.
[((UITableViewCell*) view).backgroundView.layer renderInContext:context]
But that's only a guess.
Maybe it's something simpler. When you tap a cell, selection animation is started. renderInContext ignores animations. Maybe there is a problem?

Just comment next lines:
// Center the context around the window's anchor point
// CGContextTranslateCTM(context, [view center].x, [view center].y);
// Apply the window's transform about the anchor point
// CGContextConcatCTM(context, [view transform]);
// Offset by the portion of the bounds left of and above the anchor point
// CGContextTranslateCTM(context, -[view bounds].size.width * [[view layer] anchorPoint].x, -[view bounds].size.height * [[view layer] anchorPoint].y);

Related

iOS Custom MKAnnotation object resembling MKUserLocation animation

I want to drop MKAnnotationView pins on a map and have the pins be animated much like the MKUserLocation animates (the blue dot with circular waves coming out)
How do you achieve this type of animation? What steps do I need to take?
Thanks!
Animate it like any UIView!
subclass MKAnnotationView for custom content. don't go via repeated addAnnotation calls to animate it! that is wrong
you can treat the anotationView just like any other view..
here is some code that has a blinking animation of images -- this code should get you started.
(not pretty but the exact stuff you will need for your case!)
#import "DDViewController.h"
#import <MapKit/MapKit.h>
#import <QuartzCore/QuartzCore.h>
#interface DummyAnnotation : NSObject<MKAnnotation>
#end
#implementation DummyAnnotation
- (CLLocationCoordinate2D)coordinate { return CLLocationCoordinate2DMake(51, 10); }
- (NSString *)title { return #"Dummy"; }
#end
#interface DummyAnnotationView : MKAnnotationView
#end
#implementation DummyAnnotationView
- (id)initWithAnnotation:(id <MKAnnotation>)annotation reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithAnnotation:annotation reuseIdentifier:reuseIdentifier];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectZero];
imageView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
imageView.animationImages = #[[UIImage imageNamed:#"1.gif"],[UIImage imageNamed:#"2.gif"]];
imageView.animationDuration = 5;
[imageView startAnimating];
[self addSubview:imageView];
return self;
}
#end
#interface DDViewController() <MKMapViewDelegate>
#end
#implementation DDViewController
- (MKMapView*)mapView {
return (MKMapView*)self.view;
}
- (void)viewDidLoad
{
[super viewDidLoad];
//init a region
MKCoordinateRegion region = MKCoordinateRegionMake(CLLocationCoordinate2DMake(51.0, 10.0), MKCoordinateSpanMake(2.0, 2.0));
[self.mapView setRegion:region animated:NO];
//add a dumy pin
DummyAnnotation *ann = [[DummyAnnotation alloc] init];
[self.mapView addAnnotation:ann];
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
if([annotation isKindOfClass:[DummyAnnotation class]]) {
DummyAnnotationView *view = (id)[mapView dequeueReusableAnnotationViewWithIdentifier:#"animated"];
if(!view)
view =[[DummyAnnotationView alloc ] initWithAnnotation:annotation reuseIdentifier:#"animated"];
view.bounds = CGRectMake(0, 0, 59, 59);
view.backgroundColor = [UIColor purpleColor];
//
//Animate it like any UIView!
//
CABasicAnimation *theAnimation;
//within the animation we will adjust the "opacity"
//value of the layer
theAnimation=[CABasicAnimation animationWithKeyPath:#"opacity"];
//animation lasts 0.4 seconds
theAnimation.duration=0.4;
//and it repeats forever
theAnimation.repeatCount= HUGE_VALF;
//we want a reverse animation
theAnimation.autoreverses=YES;
//justify the opacity as you like (1=fully visible, 0=unvisible)
theAnimation.fromValue=[NSNumber numberWithFloat:1.0];
theAnimation.toValue=[NSNumber numberWithFloat:0.1];
//Assign the animation to your UIImage layer and the
//animation will start immediately
[view.layer addAnimation:theAnimation forKey:#"animateOpacity"];
return view;
}
return nil;
}
//---
#end
uploaded the working sample to my dropbox (it will go away eventually but the code above is all but the image resources and the default boilerplate code of an iOS app) :: https://dl.dropbox.com/u/3753090/test.zip

Adding Gesture Recognizer for panning a UIView

After seeing some examples, I'm trying to create a window where an Image view could be moved with the PanGestureRecognizer. I don't understand what is missing.
I created and initialized an UIView object
I also created an UIGestureRecognizer for panning, for both views.
I created the method to be selected when Gesture is recognized.
If you have an idea of what is missing, I would be thankful to read it;
Here is my code:
View Controller.h
#import <UIKit/UIKit.h>
#import "bouton.h"
#interface ATSViewController : UIViewController {
boutonHome *bouton; }
#property (retain, nonatomic) boutonHome *bouton;
-(IBAction)handlePanGesture:(UIPanGestureRecognizer*)sender;
#end
View Controller.m
- (void)viewDidLoad
{
[super viewDidLoad];
UIImage *image = [UIImage imageNamed:#"back.png"];
CGRect frame = CGRectMake(0, 0, image.size.width, image.size.height);
// Set self's frame to encompass the image
bouton.frame = frame;
bouton.boutonImage = image;
[self.view addSubview:bouton];
UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(handlePanGesture:)];
[bouton setUserInteractionEnabled:YES];
[bouton addGestureRecognizer:panGesture];
[self.view setUserInteractionEnabled:YES];
[self.view addGestureRecognizer:panGesture];
// Do any additional setup after loading the view, typically from a nib.
}
-(IBAction)handlePanGesture:(UIPanGestureRecognizer *)sender
{
CGPoint translate = [sender translationInView:self.view];
CGRect newFrame = bouton.frame;
newFrame.origin.x += translate.x;
newFrame.origin.y += translate.y;
sender.view.frame = newFrame;
if(sender.state == UIGestureRecognizerStateEnded)
bouton.frame = newFrame;
}
BoutonHome.h
#import <Foundation/Foundation.h>
#interface boutonHome : UIView
{
UIImage *boutonImage;
}
#property (nonatomic, retain) UIImage *boutonImage;
// Initializer for this object
#end
boutonHome.m
#import "bouton.h"
#implementation boutonHome
#synthesize boutonImage;
#end

CALayer delegate callbacks in a UITableViewCell - Workflow

I'm using several CALayers to draw my content in a UITableViewCell subclass. The actual drawing is supposed to happen by calling the CALayer delegate method drawLayer:inContext:. However the delegate methods never gets called.
Here is my structure:
CustomCell: UITalbeViewCell
creates CustomCellContentView: UIView
creates CABackgroundLayer: CALayer
creates CATextLayer: CALayer
creates CALayerDelegate: NSObject
Each customCell has a customContentView, which holds all the CALayers for drawing.
Each customCell creates a caLayerDelegate for the CALayers to call. The caLayerDelegate reports back to the customCell.
CustomCell:
#define CALAYER_TEXTLAYER_NAME #"CATextLayer"
#define CALAYER_BGLAYER_NAME #"CABackgroundLayer"
...
- (id) customContentViewForCurrentCell
{
CGRect contentViewFrame = CGRectMake(-CC_LEFTRIGHT_PADDING, 0., self.contentView.bounds.size.width, self.contentView.bounds.size.height);
CustomCellContentView *cellContentView = [[[CustomCellContentView alloc] initWithFrame: contentViewFrame] autorelease];
CALayerDelegate *layerDelegate = [[CALayerDelegate alloc] initWithView: self];
cellContentView.layerDelegate = layerDelegate;
[cellContentView setupSubLayers];
[layerDelegate release];
return cellContentView;
}
#pragma mark - Initialisation
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (!self)
return nil;
self.customContentView = (CustomCellContentView *)[self customContentViewForCurrentCell];
self.customContentView.opaque = TRUE;
self.backgroundColor = [UIColor clearColor];
self.selectionStyle = UITableViewCellSelectionStyleNone;
[self.contentView addSubview: self.customContentView];
return self;
}
#pragma mark - Cell Update
- (void) refreshLayout
{
[self setNeedsDisplay];
[self.customContentView setNeedsDisplay];
}
...
#pragma mark - CALayer Delegate Methods
-(void) drawLayer: (CALayer*) layer inContext: (CGContextRef) context
{
}
-(void) drawCABackgroundLayer: (CALayer*) layer inContext: (CGContextRef) context
{
UIGraphicsPushContext(context);
CGRect contentRect = [layer bounds];
UIImage *bgImage = [[ImageCacheController sharedImageCache] imageFromCache: GENERIC_BGIMAGE_FILENAME];
[bgImage drawInRect: CGRectMake(contentRect.origin.x, contentRect.origin.y, contentRect.size.width, contentRect.size.height)];
UIGraphicsPopContext();
}
-(void) drawCATextLayer: (CALayer*) layer inContext: (CGContextRef) context
{
UIGraphicsPushContext(context);
CGContextSetShadowWithColor(context, CGSizeMake(0.f, 2.0f), 0.0f, [UIColor mainLabelShadowColor].CGColor);
[[UIColor mainLabelColor] set];
UIFont *mainFont = [UIFont fontWithName: FONT_INFOS size: CC_MAINLABEL_FONTSIZE_MAX];
[#"ArthurDent" drawAtPoint: [self mainViewPosition]
forWidth: CC_MAINLABEL_WIDTH
withFont: mainFont
minFontSize: CC_MAINLABEL_FONTSIZE_MAX
actualFontSize: NULL
lineBreakMode: UILineBreakModeTailTruncation
baselineAdjustment: UIBaselineAdjustmentAlignBaselines];
UIGraphicsPopContext();
}
CustomCellContentView:
#interface CustomCellContentView : UIView
{
CALayerDelegate *layerDelegate;
CALayer *backgroundLayer;
CALayer *textLayer;
}
#property (nonatomic, retain) CALayerDelegate *layerDelegate;
#property (nonatomic, retain) CALayer *backgroundLayer;
#property (nonatomic, retain) CALayer *textLayer;
- (void) setupSubLayers;
#end
#implementation CustomCellContentView
#synthesize textLayer, backgroundLayer, layerDelegate;
#pragma mark - Initialisation
- (id) initWithFrame:(CGRect)frame
{
self = [super initWithFrame: frame];
if(!self)
return nil;
return self;
}
- (void) setupSubLayers
{
self.textLayer = [CALayer layer];
self.textLayer.name = CALAYER_TEXTLAYER_NAME;
self.textLayer.shadowColor = [UIColor mainLabelShadowColor].CGColor;
self.textLayer.shadowOffset = CGSizeMake(0.0f, 2.0f);
self.textLayer.shadowOpacity = 1.f;
self.textLayer.shadowRadius = 0.f;
self.textLayer.needsDisplayOnBoundsChange = TRUE;
self.textLayer.delegate = self.layerDelegate;
self.backgroundLayer = [CALayer layer];
self.backgroundLayer.name = CALAYER_BGLAYER_NAME;
self.backgroundLayer.needsDisplayOnBoundsChange = TRUE;
self.backgroundLayer.delegate = self.layerDelegate;
[self.layer addSublayer: self.textLayer];
[self.layer addSublayer: self.backgroundLayer];
[self.textLayer setNeedsDisplay];
[self.backgroundLayer setNeedsDisplay];
}
#pragma mark - SetNeedsDisplay Overwritten
- (void) setNeedsDisplay
{
[super setNeedsDisplay];
[self.layer setNeedsDisplay];
[self.textLayer setNeedsDisplay];
[self.backgroundLayer setNeedsDisplay];
}
...
CALayerDelegate:
#implementation CALayerDelegate
#pragma mark - Initialisation
-(id) initWithView: (UIView *) view
{
self = [super init];
if (!self)
return nil;
_view = view;
return self;
}
#pragma mark - CALayer Delegate Methods
-(void) drawLayer: (CALayer*) layer inContext: (CGContextRef) context
{
NSString* methodName = [NSString stringWithFormat: #"draw%#:inContext:", [layer name]];
SEL selector = NSSelectorFromString(methodName);
if (![_view respondsToSelector: selector])
selector = #selector(drawLayer:inContext:);
[_view performSelector: selector
withObject: layer
withObject: (id)context];
}
#end
I've read for UIViewController it is better to create sub-CALayers in awakeFromNib: and not in initWithFrame:, because there is some form of layer - backing happening after the initWithFrame:, which will discard the creation of the sublayers. So, you should only add sublayers after the view is loaded?
I use seperate CALayerDelegate - objects, so the CustomCell and its view are only responsible for the customContentView.layer.
Anyone knows, what I'm doing wrong?
Thanks in advance!!
From the documentation for CALayer describing the 'delegate' property: 'In iOS, if the layer is associated with a UIView object, this property must be set to the view that owns the layer'.
If I read that correctly then you need to set CustomCellContentView as the layer delegate. Move the functionality from CALayerDelegate directly into your custom view class and see if that works. That would be the standard way to do it anyway, rather than creating a separate class just to act as a delegate.
Check that your frame is not CGRectZero.
I had a similar issue to what you describe. If the frame is CGRectZero this will prevent the drawLayer:inContext from being called.

UITableView and CALayer confusion

I got a very simple UITableViewCell subclass. MyTableViewCell.h:
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
#interface MyTableViewCell : UITableViewCell {
CALayer *backgroundLayer;
}
#end
MyTableViewCell.m:
#import "MyTableViewCell.h"
#import <QuartzCore/QuartzCore.h>
#implementation MyTableViewCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
backgroundLayer = [[CALayer alloc] init];
[backgroundLayer setBackgroundColor:[[UIColor yellowColor] CGColor]];
[[self layer] addSublayer:backgroundLayer];
}
return self;
}
- (void)layoutSublayersOfLayer:(CALayer *)layer {
[backgroundLayer setFrame:[layer frame]];
[super layoutSublayersOfLayer:layer];
}
- (void)dealloc {
[backgroundLayer release];
[super dealloc];
}
#end
Bizarrely, here's the result:.
Can someone explain this?! Why doesn't the layer paint in all cells but only every second cell?
EDIT: Here's my tableView:cellForRowAtIndexPath: method:
static NSString *reuseIdentifier = #"cellReuseIdentifier";
MyTableViewCell *cell = (MyTableViewCell *)[aTableView dequeueReusableCellWithIdentifier:reuseIdentifier];
if (cell == nil)
cell = [[[MyTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier] autorelease];
return cell;
Using this method did the trick:
- (void)layoutSublayersOfLayer:(CALayer *)layer {
CGRect frame = [layer frame];
frame.origin = CGPointZero;
[backgroundLayer setFrame:frame];
[super layoutSublayersOfLayer:layer];
}
Although not related to your question, you should add your layers to [self.contentView layer]. Otherwise editing functionality like delete-swipe will not render correctly.

How to make an infinitely long scroll view on iPhone?

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.