左右滑动视图,并且视图两侧添加左右按钮,点击按钮可以跳到前或后视图
.h文件中
#import <UIKit/UIKit.h>
@interface MyView : UIView <UIScrollViewDelegate>{
UIScrollView *scrollView;
}
@end
.m文件中
#import "MyView.h"
@implementation DutyView
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
scrollView = [[UIScrollView alloc] initWithFrame:frame];
scrollView.contentSize = CGSizeMake(frame.size.width * 10, frame.size.height);
[self addSubview:scrollView];
scrollView.delegate = self;
scrollView.pagingEnabled = YES;
scrollView.showsHorizontalScrollIndicator = NO;
for (int i = 0; i < 10; i++) {
UIImage *image = [UIImage imageNamed:@"image.jpg"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = CGRectMake(frame.size.width * i, 0, frame.size.width, frame.size.height);
[scrollView addSubview:imageView];
}
UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[leftBtn setFrame:CGRectMake(20, 35, 50, frame.size.height)];
leftBtn.tag = 50;
[leftBtn addTarget:self action:@selector(onClick:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:leftBtn];
UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[rightBtn setFrame:CGRectMake(frame.size.width - 30, 35, 50, frame.size.height)];
rightBtn.tag = 100;
[rightBtn addTarget:self action:@selector(onClick:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:rightBtn];
}
return self;
}
//点击按钮事件,跳转到前或后一个视图
-(IBAction)onClick:(id)sender{
UIButton *button = (UIButton *)sender;
CGPoint point = [scrollView contentOffset];
switch (button.tag) {
case 50:
if (point.x < scrollView.frame.size.width * 9) {
[UIView beginAnimations:@"testAnimation" context:nil];
[UIView setAnimationDuration:0.5];
[UIView setAnimationCurve:UIViewAnimationCurveLinear];
scrollView.contentOffset = CGPointMake(point.x + scrollView.frame.size.width, 0);
[UIView commitAnimations];
}
break;
case 100:
if (point.x > 0) {
[UIView beginAnimations:@"testAnimation" context:nil];
[UIView setAnimationDuration:0.5];
[UIView setAnimationCurve:UIViewAnimationCurveLinear];
scrollView.contentOffset = CGPointMake(point.x - scrollView.frame.size.width, 0);
[UIView commitAnimations];
}
break;
default:
break;
}
}
- (void)dealloc {
[scrollView release];
[super dealloc];
}
@end