[[self.view subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
或者
NSArray *viewsToRemove = [self.view subviews]; for (UIView *view in viewsToRemove) { [view removeFromSuperview]; }
//FaceView.m文件
@implementation FaceView -(id)initWithFrame:(CGRect)frame{ self=[super initWithFrame:frame]; if (self) { } return self; } //自己实现drawRect方法重绘 ,也可以不实现该方法,自己定义执行界面处理方法执行 -(void) drawRect:(CGRect)rect{ //省略实现。。。 } @end
将要加载的view放在主window上或者根视图控制器上,利用transform将视图等比缩放
下面将一个视图在AppDelegate中处理
FloatingView *view=[[FloatingView alloc] initWithFrame:CGRectMake(50, 50, 200, 200)]; //添加拖动手势,使视图达到悬浮窗的拖动效果 UIPanGestureRecognizer *panGestures=[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGestures:)]; [view addGestureRecognizer:panGestures]; //单击视图手势 UITapGestureRecognizer *tapGestures=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(narrowView:)]; [view addGestureRecognizer:tapGestures]; [self.window addSubview:view];
//点击等比缩小视图 -(void)narrowView:(UITapGestureRecognizer *)sender{ //等比缩放视图 sender.view.transform=CGAffineTransformScale(sender.view.transform, 0.5, 0.5); } //处理视频视图拖动事件 -(void)handlePanGestures:(UIPanGestureRecognizer *)sender{ if(sender.state!=UIGestureRecognizerStateEnded&&sender.state!=UIGestureRecognizerStateFailed) { //通过使用 locationInView 这个方法,来获取到手势的坐标 CGPoint location=[sender locationInView:sender.view.superview]; sender.view.center=location; } }
//TouchView.h文件
#import <UIKit/UIKit.h> @interface TouchView : UIView @property(nonatomic,strong) NSMutableArray *points,*pointsTem; @end
//TouchView.m文件
#import "TouchView.h" @implementation TouchView - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { self.backgroundColor=[UIColor whiteColor]; self.points=[[NSMutableArray alloc] init]; } return self; } //设置为单点触控,不支持多点触控 -(BOOL)isMultipleTouchEnabled{ return NO; } //开始触摸,创建一个新的pointsTem的array,并记录点 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ self.pointsTem=[[NSMutableArray alloc] init]; CGPoint pt=[[touches anyObject] locationInView:self]; //将点通过NSValue包装成对象类型 [self.pointsTem addObject:[NSValue valueWithCGPoint:pt]]; [self.points addObject:self.pointsTem]; } //移动过程中记录各个点 -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ CGPoint pt=[[touches anyObject] locationInView:self]; //将点通过NSValue包装成对象类型 [self.pointsTem addObject:[NSValue valueWithCGPoint:pt]]; [self.points addObject:self.pointsTem]; //标志着接收机的整个边界矩形需要重绘,这又会调用drawRect:的调用 [self setNeedsDisplay]; } //绘制 -(void)drawRect:(CGRect)rect{ if (!self.points) { return; } if (!(self.points.count>0)) { return; } //设置后面绘制线条的颜色 [[UIColor blackColor] set]; //设置Quartz2D的绘制环境 CGContextRef context=UIGraphicsGetCurrentContext(); //图像上下文和线宽设置 CGContextSetLineWidth(context, 4.0f); NSValue *objectFromArray; //通过获取array里面的arry实现画多条线 for (int i=0; i<(self.points.count-1); i++) { if (![self.points objectAtIndex:i]) { continue; } NSMutableArray *pointsTemDraw=[self.points objectAtIndex:i]; if (pointsTemDraw.count<2) { continue; } for (int j=0; j<(pointsTemDraw.count-1); j++) { objectFromArray=[pointsTemDraw objectAtIndex:j]; CGPoint pt1=[objectFromArray CGPointValue]; objectFromArray=[pointsTemDraw objectAtIndex:(j+1)]; CGPoint pt2=[objectFromArray CGPointValue]; //开始一个新的移动点 CGContextMoveToPoint(context, pt1.x, pt1.y); //附件一条线到当前点 CGContextAddLineToPoint(context, pt2.x, pt2.y); //在当前路径画一条线 CGContextStrokePath(context); } } } @end
//上面的方式笔画太多后UI效果跟不上性能太差,下面是新的方式
// TKTouchView.h
// // TKTouchView.h // 手势签名 // // Created by Vie on 15/8/31. // Copyright (c) 2015年 Vie. All rights reserved. // #import <UIKit/UIKit.h> @interface TKTouchView : UIView @property(nonatomic,strong) UIButton *cleanBtn;//清除按钮 @end
// TouchView.m
// // TouchView.m // DrawImageView // // Created by Vie on 15/8/31. // Copyright (c) 2015年 Vie. All rights reserved. // #import "TKTouchView.h" @implementation TKTouchView { UIBezierPath *beizerPath; UIImage *incrImage; CGPoint points[5]; uint control; } - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { self.backgroundColor=[UIColor whiteColor]; float cleanBtnWidth=38; float cleanBtnHeight=33; self.cleanBtn=[[UIButton alloc] initWithFrame:CGRectMake(0, self.frame.size.height-cleanBtnHeight-5, cleanBtnWidth, cleanBtnHeight)]; self.cleanBtn.layer.cornerRadius=2.0f; self.cleanBtn.layer.borderColor=[[UIColor grayColor] CGColor]; self.cleanBtn.layer.borderWidth=0.3f; [self.cleanBtn setTitle:@"清除" forState:UIControlStateNormal]; [self.cleanBtn.titleLabel setFont:[UIFont fontWithName:@"Helvetica-Bold"size:16.0f]]; [self.cleanBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal]; self.cleanBtn.transform=CGAffineTransformMakeRotation(M_PI/2); [self.cleanBtn addTarget:self action:@selector(cleanAction:) forControlEvents:UIControlEventTouchUpInside]; [self addSubview:self.cleanBtn]; [self setMultipleTouchEnabled:NO]; beizerPath = [UIBezierPath bezierPath]; [beizerPath setLineWidth:4.0]; } return self; } //清除签名 -(void)cleanAction:(UIButton *)sender{ incrImage = nil; [self setNeedsDisplay]; } //设置为单点触控,不支持多点触控 -(BOOL)isMultipleTouchEnabled{ return NO; } //开始触摸,创建一个新的pointsTem的array,并记录点 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ control = 0; UITouch *touch = [touches anyObject]; points[0] = [touch locationInView:self]; CGPoint startPoint = points[0]; CGPoint endPoint = CGPointMake(startPoint.x + 1.5, startPoint.y + 2); [beizerPath moveToPoint:startPoint]; [beizerPath addLineToPoint:endPoint]; } //移动过程中记录各个点 -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ UITouch *touch = [touches anyObject]; CGPoint touchPoint = [touch locationInView:self]; control++; points[control] = touchPoint; if (control == 4) { points[3] = CGPointMake((points[2].x + points[4].x)/2.0, (points[2].y + points[4].y)/2.0); [beizerPath moveToPoint:points[0]]; [beizerPath addCurveToPoint:points[3] controlPoint1:points[1] controlPoint2:points[2]]; [self setNeedsDisplay]; points[0] = points[3]; points[1] = points[4]; control = 1; } } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { [self drawBitmapImage]; [self setNeedsDisplay]; [beizerPath removeAllPoints]; control = 0; } - (void)drawBitmapImage { UIGraphicsBeginImageContextWithOptions(self.bounds.size, YES, 0.0); if (!incrImage) { UIBezierPath *rectpath = [UIBezierPath bezierPathWithRect:self.bounds]; [[UIColor whiteColor] setFill]; [rectpath fill]; } [incrImage drawAtPoint:CGPointZero]; //Set final color for drawing UIColor *strokeColor = [UIColor redColor]; [strokeColor setStroke]; [beizerPath stroke]; incrImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); } - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event { [self touchesEnded:touches withEvent:event]; } //绘制 -(void)drawRect:(CGRect)rect{ [incrImage drawInRect:rect]; [beizerPath stroke]; // Set initial color for drawing UIColor *fillColor = [UIColor redColor]; [fillColor setFill]; UIColor *strokeColor = [UIColor redColor]; [strokeColor setStroke]; [beizerPath stroke]; } @end
*ios4提供的方法:
- (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight
这个函数是UIImage的一个实例函数,它的功能是创建一个内容可拉伸,而边角不拉伸的图片,需要两个参数,第一个是不拉伸区域距离左边框的宽度,第二个参数是不拉伸区域距离上边框的宽度,其操作本质是对一个像素的复制拉伸,故没有渐变效果,这也是其缺点所在。
参数的意义是,如果参数指定10,5。那么,图片左边10个点,上边5个点。不会被拉伸,x坐标为11的点会被横向复制,y坐标为6的点会被纵向复制。注意:只是对一个点像素进行复制到指定的宽度。
*ios5提供的方法:
- (UIImage *)resizableImageCapInsets:(UIEdgeInsets)Insets
其中Insets这个参数的格式是(top,left,bottom,right),从上、左、下、右分别在图片上画了一道线,这样就给一个图片指定了一个矩形区域。只有在框里面的部分才会被拉伸,而框外面的部分则保持改变。比如(20,5,10,5),意思是下图矩形里面的部分可以被拉伸,而其余部分不变。
*ios6提供的方法:
- (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets resizingMode:(UIImageResizingMode)resizingMode
关于Insets参数,与ios5是相同的,不同的是其后增加了一个拉伸的模式,ios6.0的版本提供了
UIImageResizingModeTile和 UIImageResizingModeStretch两种模式,从名字就可以看出,是平铺模式和拉伸模式。平铺就是复制你Insets指定的矩形区域块来填充你所指定的图片区域,而拉伸就是通过拉伸你Insets指定的矩形区域块来填充你 所需的图片区域。图片的resize由一个点变成了一个矩形块,这样你的所指定块的渐变效果,也是可以呈现出来的。
示例:
float bgImgViewX=self.frame.size.width-90-messageSize.width; //背影图片 UIImage *bgImg=[UIImage imageNamed:@"send_bg.png"]; self.bgImgView=[[UIImageView alloc] initWithImage:[bgImg resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 15) resizingMode:UIImageResizingModeStretch]]; self.bgImgView.frame = CGRectMake(bgImgViewX, 14.0f, messageSize.width+30.0f, messageSize.height+20.0f);
计算文本要占用的空间大小
//CGSizeMake(200, 500)是允许最大占范围 CGSize messageSize=[messageText boundingRectWithSize:CGSizeMake(200, 500) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:20.0f]} context:nil].size;
UILable文字增加阴影效果
//文本加阴影
self.messageLable.shadowColor=[UIColor blackColor];
//正数右下角有阴影效果,负数左上角有阴影效果
self.messageLable.shadowOffset=CGSizeMake(0, 1.0);
设置按钮边框颜色,边框线大小
//设置按钮边框线粗细
[self.twoVideoBtn.layer setBorderWidth:1.0f];
//设置按钮边框颜色
self.twoVideoBtn.layer.borderColor = [[UIColor colorWithRed:193/255.0green:193/255.0 blue:193/255.0 alpha:1] CGColor];
UISegmentedControl *segmentedControl=[[UISegmentedControl alloc] initWithItems:@[@"One",@"Two",@"Three"]]; //设置默认选中栏,按下标从零开始。 segmentedControl.selectedSegmentIndex=0; //momentary设置为YES,不显示选择状态 //segmentedControl.momentary=YES; [segmentedControl addTarget:self action:@selector(changedValue:) forControlEvents:UIControlEventValueChanged]; self.navigationItem.titleView=segmentedControl;
-(void)changedValue:(UISegmentedControl *)sender{ // int x= sender.selectedSegmentIndex; }
//UIScrollView(滚动视图)和UIPageControl(指示器)简单使用
//Test4ViewController.m"文件 #import "Test4ViewController.h" @interface Test4ViewController () @property (strong,nonatomic)UIScrollView *scrollView; @property (strong,nonatomic)UIPageControl *pageControl; @end @implementation Test4ViewController - (void)viewDidLoad { [super viewDidLoad]; [self.view setBackgroundColor:[UIColor whiteColor]]; //初始化scrollView视图大小 _scrollView=[[UIScrollView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height*0.1, self.view.frame.size.width, self.view.frame.size.height*0.8)]; //是否支持分页 _scrollView.pagingEnabled=YES; //指定控件是否只能在一个方向上滚动(默认为NO) _scrollView.directionalLockEnabled=YES; //设置水平指示滚动标不可见 _scrollView.showsHorizontalScrollIndicator = NO; //设置内容尺寸,内容比视图大即可滑动,什么方向滑动取决于内容什么方向上比视图大 CGSize newSize = CGSizeMake(self.view.frame.size.width * 3, self.view.frame.size.height*0.2); [_scrollView setContentSize:newSize]; //设置滚动的开始视图 _scrollView.contentOffset = CGPointMake(0, 0); //设置委托 _scrollView.delegate = self; [self.view addSubview:_scrollView]; // 初始化 pagecontrol提供一行点来指示当前显示的是多页面视图的哪一页,以便让页面控件看起来更像一个指示器 _pageControl=[[UIPageControl alloc] initWithFrame:CGRectMake(self.view.frame.size.width*0.3, 200, self.view.frame.size.width*0.3, 18)]; //pageControl长度 _pageControl.numberOfPages=3; //pageControl初始化值 _pageControl.currentPage=0; //当前页面指示器颜色 [_pageControl setCurrentPageIndicatorTintColor:[UIColor redColor]]; //非当前页面指示器颜色 [_pageControl setPageIndicatorTintColor:[UIColor blackColor]]; [_pageControl addTarget:self action:@selector(changePage:) forControlEvents:UIControlEventValueChanged]; [self.view addSubview:_pageControl]; UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 200, 320, self.view.frame.size.height*0.2)]; label.backgroundColor = [UIColor yellowColor]; label.text = @"学习scrolleview"; [_scrollView addSubview:label]; UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width, 200, 320, self.view.frame.size.height*0.2)]; label2.backgroundColor = [UIColor yellowColor]; label2.text = @"学习scrolleviewtwo"; [_scrollView addSubview:label2]; UILabel *label3 = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width*2, 200, 320, self.view.frame.size.height*0.2)]; label3.backgroundColor = [UIColor yellowColor]; label3.text = @"学习scrolleview333"; [_scrollView addSubview:label3]; } //开始滚动委托函数 -(void)scrollViewDidScroll:(UIScrollView *)scrollView{ //获取当前视图页面的的x坐标计算下为page值 int page=scrollView.contentOffset.x/(self.view.frame.size.width); //改变指示器值 self.pageControl.currentPage=page; } //结束滚动委托函数 -(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{ } -(void)changePage:(UIPageControl *)sender{ //获取当前页面的page值 int page=sender.currentPage; //改名scrollView界面 self.scrollView.contentOffset = CGPointMake(self.view.frame.size.width*page, 0); } @end
用UIScrollView实现,tableView的cell左侧滑动
效果图:
//SlideTableViewController.h文件
#import <UIKit/UIKit.h> @interface SlideTableViewController : UIViewController<UITableViewDataSource,UITableViewDelegate> @property (strong,nonatomic) NSMutableArray *tbArray;//数据 @property (strong,nonatomic) UIScrollView *myScrollView;//用于记住滑动完成的scrollView @end
//SlideTableViewController.m文件
#import "SlideTableViewController.h" @implementation SlideTableViewController - (void)viewDidLoad { [super viewDidLoad]; [self.view setBackgroundColor:[UIColor whiteColor]]; //创建视图 UITableView *uiTable=[[UITableView alloc] initWithFrame:self.view.frame]; //分割线颜色 uiTable.separatorColor=[UIColor lightGrayColor]; [uiTable.layer setCornerRadius:5.0]; //完成布局 [self.view addSubview:uiTable]; uiTable.dataSource=self; uiTable.delegate=self; self.tbArray=[[NSMutableArray alloc] initWithObjects:@"风继续吹",@"真的爱你",@"透明的你",@"爱的太迟",@"Dear friends",@"永远不回头",@"突然想起你",@"遥远的他",@"一颗滚石",@"真的爱你", nil]; } //指定每个分区的单元格数量 -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ return [self.tbArray count]; } //设置单元格 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString *cellDo=@"cellDo"; UITableViewCell *cell=(UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellDo]; if (!cell) { cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:cellDo]; } // cell.textLabel.text=[self.tbArray objectAtIndex:indexPath.row]; UITextView *textView=[[UITextView alloc] initWithFrame:CGRectMake(10, 0, self.view.frame.size.width-10, 44)]; textView.text=[self.tbArray objectAtIndex:indexPath.row];; textView.textColor=[UIColor blackColor]; textView.textAlignment=NSTextAlignmentLeft; textView.editable=false; UIButton *btn3 = [UIButton buttonWithType:UIButtonTypeRoundedRect]; btn3.frame = CGRectMake(self.view.frame.size.width,0, 44, 44.0f); btn3.backgroundColor=[UIColor blackColor]; [btn3 setTitle:@"粉丝" forState:UIControlStateNormal]; UIButton *btn4 = [UIButton buttonWithType:UIButtonTypeRoundedRect]; btn4.frame = CGRectMake(self.view.frame.size.width+44, 0, 44, 44.0f); [btn4 setTitle:@"话题" forState:UIControlStateNormal]; //设置视图大小 UIScrollView *scrollView=[[UIScrollView alloc] initWithFrame:CGRectMake(0,0, self.view.frame.size.width, 44)]; //设置水平指示滚动标不可见 scrollView.showsHorizontalScrollIndicator = NO; //设置范围,每块分区以视图大小为准 CGSize newSize = CGSizeMake(self.view.frame.size.width+88, 44); [scrollView setContentSize:newSize]; scrollView.delegate=self; //添加单机手势 UITapGestureRecognizer *tapGes=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)]; //设置点按次数 [tapGes setNumberOfTapsRequired:1]; [scrollView addGestureRecognizer:tapGes]; [scrollView addSubview:btn3]; [scrollView addSubview:btn4]; [scrollView addSubview:textView]; //添加视图 [cell.contentView addSubview:scrollView]; return cell; } //将上一个滚动视图还原 -(void)tapAction:(UITapGestureRecognizer *)sender{ self.myScrollView.contentOffset=CGPointMake(0, 0); } //开始滚动时,如果上一个是改视图,则不还原 -(void)scrollViewDidScroll:(UIScrollView *)scrollView{ if (!(self.myScrollView==scrollView)) { self.myScrollView.contentOffset=CGPointMake(0, 0); } } -(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath*)indexPath{ return YES; } //结束滚动时,获取到scrollview -(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{ self.myScrollView=scrollView; } @end
// ViewController.m
// // ViewController.m // TableViewTest // // Created by Vie on 15/9/14. // Copyright (c) 2015年 Vie. All rights reserved. // #import "ViewController.h" #define MAINLABEL ((UILabel *)self.navigationItem.titleView) //遵守协议 @interface ViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate,UISearchResultsUpdating> @property(nonatomic,strong) UITableView *tbView; @property(nonatomic,strong) NSMutableArray *array,*searchArray; @property (nonatomic, strong) UISearchController *searchController; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self.view setBackgroundColor:[UIColor whiteColor]]; self.navigationItem.titleView=[[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 200.0f, 30.0f)]; [MAINLABEL setTextColor:[UIColor blackColor]]; [MAINLABEL setTextAlignment:NSTextAlignmentCenter]; [MAINLABEL setText:@"Default"]; self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc] initWithTitle:@"Add" style:UIBarButtonItemStylePlain target:selfaction:@selector(addAction:)]; self.tbView=[[UITableView alloc] initWithFrame:self.view.frame]; self.tbView.dataSource=self; self.tbView.delegate=self; self.array=[[NSMutableArray alloc] init]; //将字体样式值赋给array for (int i=0; i<[UIFont familyNames].count; i++) { [self.array addObject:[[UIFont familyNames] objectAtIndex:i]]; } self.searchArray=[[NSMutableArray alloc] init]; //设置为可编辑 // [self.tbView setEditing:YES animated:YES]; [self.view addSubview:self.tbView]; _searchController = [[UISearchController alloc] initWithSearchResultsController:nil]; _searchController.searchResultsUpdater = self; _searchController.dimsBackgroundDuringPresentation = NO; _searchController.hidesNavigationBarDuringPresentation = NO; _searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 44.0); _searchController.searchBar.placeholder=@"输入查找内容"; self.tbView.tableHeaderView = self.searchController.searchBar; } //创建分段索引 -(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{ NSMutableArray *array=[NSMutableArray arrayWithObjects:@"X",@"Y",@"Z", nil]; return array; } //搜索栏改变时回调 -(void)updateSearchResultsForSearchController:(UISearchController*)searchController{ NSString *searchString=[self.searchController.searchBar text]; NSPredicate *preicate=[NSPredicate predicateWithFormat:@"SELF CONTAINS[c] %@",searchString]; if (self.searchArray!=nil) { [self.searchArray removeAllObjects]; } //过滤数据 self.searchArray=[NSMutableArray arrayWithArray:[self.arrayfilteredArrayUsingPredicate:preicate]]; //刷新表格 [self.tbView reloadData]; } //完成移动的触发事件,不添加该方法不能实现移动功能 -(void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath*)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{ //在移动的时候将被移动的单元格数据按照新的位置放置数据源中 NSString *moveStr=[self.array objectAtIndex:sourceIndexPath.row]; [self.array removeObjectAtIndex:sourceIndexPath.row]; [self.array insertObject:moveStr atIndex:destinationIndexPath.row]; //重新加载数据,验证数据源的位置是否对应改变(用完注释掉) // [self.tbView reloadData]; } //添加数据到arry,重新加载数据,实现添加单元格 -(void)addAction:(id)sender{ [self.array insertObject:@"add" atIndex:0]; [self.tbView reloadData]; } //处理tableView对象编辑 -(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath*)indexPath{ if (editingStyle==UITableViewCellEditingStyleDelete) { //搜索时将搜索的数据也删除,其他删除源数据 if (self.searchController.active){ [self.searchArray removeObjectAtIndex:indexPath.row]; }else{ [self.array removeObjectAtIndex:indexPath.row]; } [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationFade]; } } //用户选中单元格时回调 -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath{ //改变导航栏的文字和字体。 NSString *font=[self.array objectAtIndex:indexPath.row]; [MAINLABEL setText:font]; [MAINLABEL setFont:[UIFont fontWithName:font size:18.0f]]; //获取到单元格 UITableViewCell *cell=[tableView cellForRowAtIndexPath:indexPath]; //改变左侧图像 cell.imageView.image=[UIImage imageNamed:@"娜美.jpg"]; //单元格右侧添加蓝色勾选样式 cell.accessoryType=UITableViewCellAccessoryCheckmark; } //绘制单元格cell -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ //以indexPath来唯一确定cell,每个单元格重用标示唯一,防止重用机制导致的内容出错 NSString *CellIdentifier = [NSString stringWithFormat:@"cell%ld%ld", (long)[indexPath section], (long)[indexPath row]]; //返回一个可重用的表视图单元格对象位置的标识符,并转换为单元格类型 UITableViewCell *cell=(UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (!cell) { cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitlereuseIdentifier:CellIdentifier]; } //去掉单元格选中高亮状态样式 cell.selectionStyle=UITableViewCellSelectionStyleNone; if (self.searchController.active) { cell.textLabel.text=[self.searchArray objectAtIndex:indexPath.row]; }else{ cell.textLabel.text=[self.array objectAtIndex:indexPath.row]; } return cell; } //指定分区 -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ return 1; } //指定分区单元格数 -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ if (self.searchController.active) { return self.searchArray.count; }else{ return self.array.count; } // return self.array.count; } @end
//效果图
//ViewController.h文件
// // ViewController.h // UseUICollectionView // // Created by Vie on 2016/11/3. // Copyright © 2016年 Vie. All rights reserved. // #import <UIKit/UIKit.h> @interface ViewController : UIViewController @end
//ViewController.m
// // ViewController.m // UseUICollectionView // // Created by Vie on 2016/11/3. // Copyright © 2016年 Vie. All rights reserved. // #import "ViewController.h" #import "MyCollectionViewCell.h" @interface ViewController ()<UICollectionViewDelegate,UICollectionViewDataSource> @property(nonatomic,strong) NSArray *array; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init]; UICollectionView *collView=[[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout]; collView.backgroundColor=[UIColor whiteColor]; collView.dataSource=self; collView.delegate=self; //注册单元格使用的类型,必须先注册,否则会报异常 [collView registerClass:[MyCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([MyCollectionViewCell class])]; // //注册头 // [collView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"]; // //注册脚 // [collView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer"]; [self.view addSubview:collView]; } #pragma mark -设置当前item是否可以点击 -(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath{ if (indexPath.row%2==0) { return NO; }else{ return YES; } } #pragma mark -点击item时触发 -(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{ NSLog(@"您点击了item%@",[[self array] objectAtIndex:indexPath.row]); if ([collectionView cellForItemAtIndexPath:indexPath].backgroundColor==[UIColor blackColor]) { [collectionView cellForItemAtIndexPath:indexPath].backgroundColor=[UIColor colorWithRed:arc4random()%255/255.0 green:arc4random()%255/255.0 blue:arc4random()%255/255.0 alpha:1]; }else{ [collectionView cellForItemAtIndexPath:indexPath].backgroundColor=[UIColor blackColor]; } } #pragma mark -设置分区 -(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{ return 1; } #pragma mark -设置分区内单元格数量 -(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{ return self.array.count; } #pragma mark -设置每个item的大小 -(CGSize)collectionView:(UICollectionView *)collectionView layout:(nonnull UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(nonnull NSIndexPath *)indexPath{ if (indexPath.row%2==0) { return CGSizeMake(99, 99); }else{ return CGSizeMake(99, 99); } } #pragma mark -设置每个分区的边距 -(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(nonnull UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{ return UIEdgeInsetsMake(20, 10, 20, 10); } #pragma mark -设置单元格 -(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath{ //设置的单元格要与Identifier注册的一致 MyCollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([MyCollectionViewCell class]) forIndexPath:indexPath]; NSLog(@"%@",[[self array] objectAtIndex:indexPath.row]); cell.titleStr=[[self array] objectAtIndex:indexPath.row]; cell.backgroundColor = [UIColor colorWithRed:arc4random()%255/255.0 green:arc4random()%255/255.0 blue:arc4random()%255/255.0 alpha:1]; // cell.contentView return cell; } /*item垂直间距*/ - (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section { return 1; } /*item水平间距*/ - (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section { return 1; } -(NSArray *)array{ if (!_array) { _array=[NSArray arrayWithObjects:@"李一",@"虎二",@"张三",@"李四",@"王五",@"赵六",@"陈七",@"刘九",@"夏十", nil]; } return _array; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
//MyCollectionViewCell.h
// // MyCollectionViewCell.h // UseUICollectionView // // Created by Vie on 2016/11/3. // Copyright © 2016年 Vie. All rights reserved. // #import <UIKit/UIKit.h> @interface MyCollectionViewCell : UICollectionViewCell @property(nonatomic,strong) NSString *titleStr; @end
//MyCollectionViewCell.m
// // MyCollectionViewCell.m // UseUICollectionView // // Created by Vie on 2016/11/3. // Copyright © 2016年 Vie. All rights reserved. // #import "MyCollectionViewCell.h" @interface MyCollectionViewCell() @property(nonatomic,strong) UILabel *titleLable; @end @implementation MyCollectionViewCell -(instancetype)initWithFrame:(CGRect)frame{ self=[super initWithFrame:frame]; if (self) { [self darwView]; } return self; } -(void)setTitleStr:(NSString *)titleStr{ _titleLable.text=titleStr; } -(void)darwView{ [self addSubview:[self titleLable]]; } -(UILabel *)titleLable{ if (!_titleLable) { _titleLable=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 99, 99)]; _titleLable.textColor=[UIColor whiteColor]; _titleLable.textAlignment=NSTextAlignmentCenter; } return _titleLable; } @end
// UICollectionView 受 NavigationBarHidden 影响,自动滚动调整,修复collectionView偏移
//自动滚动调整,修复collectionView偏移 self.automaticallyAdjustsScrollViewInsets = NO;
或者让约束或者布局从导航栏底部开始算起(导航栏底部为Y轴0)
//右侧小红勾
cell.accessoryType=UITableViewCellAccessoryCheckmark;
cell.tintColor=[UIColor redColor];
//右侧灰色小箭头
cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
//右侧蓝色i符号加灰色小箭头
cell.accessoryType=UITableViewCellAccessoryDetailDisclosureButton;
//右侧蓝色i符号
cell.accessoryType=UITableViewCellAccessoryDetailButton;
//左右侧的图片
UIImage *stetchLeftTrack= [UIImage imageNamed:@"left_bar.png"];
UIImage *stetchRightTrack = [UIImage imageNamed:@"right_bar.png"];
//滑块图片
UIImage *thumbImage = [UIImage imageNamed:@"mark.png"];
UISlider *slider=[[UISlider alloc]initWithFrame:CGRectMake(30, 320, 257, 7)];
slider.backgroundColor = [UIColor clearColor];
slider.value=0.3;
slider.minimumValue=0.0;
slider.maximumValue=1.0;
[slider setMinimumTrackImage:stetchLeftTrack forState:UIControlStateNormal];
[slider setMaximumTrackImage:stetchRightTrack forState:UIControlStateNormal];
//注意这里要加UIControlStateHightlighted的状态,否则当拖动滑块时滑块将变成原生的控件
[slider setThumbImage:thumbImage forState:UIControlStateHighlighted];
[slider setThumbImage:thumbImage forState:UIControlStateNormal];
//滑块拖动时的事件
[slider addTarget:self action:@selector(sliderValueChanged:) forControlEvents:UIControlEventValueChanged];
//滑动拖动后的事件
[slider addTarget:self action:@selector(sliderDragUp:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:slider];
//GuidePageView.h
// // GuidePageView.h // 引导页视图 // // Created by Vie on 2017/11/15. // Copyright © 2017年 Vie. All rights reserved. // #import <UIKit/UIKit.h> @interface GuidePageView : UIView /** @author Vie,2017年11月15日11:05:13 初始化引导页视图 @param frame 布局 @param imgArray 引导图组(没有引导图为空白视图) @return instancetype */ -(instancetype)initWithFrame:(CGRect)frame imgArray:(NSArray *)imgArray; @end
//GuidePageView.m
// // GuidePageView.m // 引导页视图 // // Created by Vie on 2017/11/15. // Copyright © 2017年 Vie. All rights reserved. // #import "GuidePageView.h" @interface GuidePageView()<UIScrollViewDelegate> @property (nonatomic,strong) UIScrollView *scrollView;//引导页滚动视图 @property (nonatomic,strong) UIPageControl *pageControl;//滚动指示器 @property (nonatomic,strong) NSArray *imgArray;//引导页图组 @property (nonatomic,strong) UIButton *startBtn;//开始体验按钮 @end @implementation GuidePageView /** @author Vie,2017年11月15日11:05:13 初始化引导页视图 @param frame 布局 @param imgArray 引导图组(没有引导图为空白视图) @return instancetype */ -(instancetype)initWithFrame:(CGRect)frame imgArray:(NSArray *)imgArray{ self=[super initWithFrame:frame]; if (self&&imgArray.count>0) { self.imgArray=imgArray; [self loadView]; } return self; } -(void)loadView{ [self addSubview:self.scrollView]; [self addSubview:self.pageControl]; [self addSubview:self.startBtn]; } #pragma mark delegate //滚动结束委托函数 -(void)scrollViewDidScroll:(UIScrollView *)scrollView{ //获取当前视图页面的的x坐标计算下为page值 int page=scrollView.contentOffset.x/(self.frame.size.width); //改变指示器值 self.pageControl.currentPage=page; [self changStatusWithPage:page]; } #pragma mark action /** @author Vie,2017年11月17日10:01:59 滚动指示器改变值 @param sender 滚动指示器 */ -(void)changePage:(UIPageControl *)sender{ //获取当前页面的page值 NSInteger page=sender.currentPage; //改名scrollView界面 self.scrollView.contentOffset = CGPointMake(self.frame.size.width*page, 0); [self changStatusWithPage:page]; } /** @author Vie,2017年11月17日10:01:59 改变开始体验按钮显示状态 @param page 当前页面下标 */ -(void)changStatusWithPage:(NSInteger)page{ if (page==self.imgArray.count-1) { self.startBtn.hidden=NO; }else{ self.startBtn.hidden=YES; } } /** @author Vie,2017年11月17日11:34:20 开始体验移除引导图 @param sender 点击按钮 */ -(void)btnAction:(UIButton *)sender{ [self removeFromSuperview]; } #pragma mark lazyloading /** @author Vie,2017年11月14日16:25:31 滚动视图懒加载 */ -(UIScrollView *)scrollView{ if (!_scrollView) { //初始化scrollView _scrollView=[[UIScrollView alloc] initWithFrame:self.frame]; //是否支持分页 _scrollView.pagingEnabled=YES; //指定控件是否只能在一个方向上滚动(默认为NO) _scrollView.directionalLockEnabled=YES; //设置水平指示滚动标不可见 _scrollView.showsHorizontalScrollIndicator = NO; //设置范围,宽为引导图组数量的fram宽度,可以以左右滑动 CGSize spaceSize = CGSizeMake(self.frame.size.width * self.imgArray.count, 0); [_scrollView setContentSize:spaceSize]; //设置滚动的开始视图 _scrollView.contentOffset = CGPointMake(0, 0); //滚动视图是否能滚动超过边界 _scrollView.bounces = NO; //设置委托 _scrollView.delegate = self; //引导图组 for (int i=0; i<self.imgArray.count; i++) { UIImageView *imgView=[[UIImageView alloc] initWithFrame:CGRectMake(self.frame.size.width*i, 0, self.frame.size.width, self.frame.size.height)]; imgView.image=[UIImage imageNamed:self.imgArray[i]]; [_scrollView addSubview:imgView]; } } return _scrollView; } /** @author Vie,2017年11月17日09:57:53 滚动指示器懒加载 */ -(UIPageControl *)pageControl{ if (!_pageControl) { // 初始化 pagecontrol提供一行点来指示当前显示的是多页面视图的哪一页,以便让页面控件看起来更像一个指示器 _pageControl=[[UIPageControl alloc] initWithFrame:CGRectMake(0, self.frame.size.height*0.8-25, self.frame.size.width, 18)]; //pageControl长度 _pageControl.numberOfPages=self.imgArray.count; //pageControl初始化值 _pageControl.currentPage=0; //当前页面指示器颜色 [_pageControl setCurrentPageIndicatorTintColor:[UIColor orangeColor]]; //非当前页面指示器颜色 [_pageControl setPageIndicatorTintColor:[UIColor grayColor]]; [_pageControl addTarget:self action:@selector(changePage:) forControlEvents:UIControlEventValueChanged]; } return _pageControl; } /** @author Vie,2017年11月17日10:43:24 开始体验按钮懒加载 */ -(UIButton *)startBtn{ if (!_startBtn) { _startBtn=[[UIButton alloc] initWithFrame:CGRectMake((self.frame.size.width-150)/2, self.frame.size.height*0.8, 150, 50)]; _startBtn.backgroundColor=[UIColor orangeColor]; [_startBtn setTitle:@"开 始 体 验" forState:UIControlStateNormal]; [_startBtn setTitleColor:[VUIHelper colorWithString:@"ffffff"] forState:UIControlStateNormal]; _startBtn.titleLabel.font=[UIFont systemFontOfSize:20.0f]; _startBtn.layer.cornerRadius=5.0f; _startBtn.hidden=YES; [_startBtn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside]; } return _startBtn; } @end
//使用在AppDelegate中
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { RootViewController *rootCtr=[[RootViewController alloc] init]; self.window=[[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; self.window.rootViewController=rootCtr; [self.window makeKeyAndVisible]; [self isShowGuidPage]; return YES; } /** @author Vie,2017年11月17日14:15:25 当前版本是否展示引导页 */ -(void)isShowGuidPage{ NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary]; // app版本 NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"]; //获取当前版本是否展示过引导页 NSString *isPage=[[NSUserDefaults standardUserDefaults] objectForKey:app_Version]; if (![isPage isEqualToString:@"1"]) { NSArray *imgArray=[[NSArray alloc] initWithObjects:@"1.JPG",@"2.JPG",@"1.JPG",@"2.JPG", nil]; GuidePageView *guideView=[[GuidePageView alloc] initWithFrame:[UIScreen mainScreen].bounds imgArray:imgArray]; [self.window addSubview:guideView]; [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:app_Version]; [[NSUserDefaults standardUserDefaults] synchronize]; } }
运行效果