首页 文章 精选 留言 我的

精选列表

搜索[ios],共10000篇文章
优秀的个人博客,低调大师

学习ios【2】Objective-C 数字和字符串

一 数字 1.使用Foundation.h可以直接导入所有的头文件。 在XCode中,想查看某个方法帮助,可以将光标放在方法上,按住option键同时单击即可。 官方文档: https://developer.apple.com/library/mac/navigation/ 2.数字对象 objective-c有几种基本数据类型,int float long等,不过有些时候比如NSArray需要使用数字对象,而前面几种基本数据类型并不是对象,此时我们可以使用NSNumber. 对于每种基本数据类型,类方法都可以为它创建一个NSNumber对象,并设定值。这些方法都是以numberWith开头,如numberWithInteger等。也可以使用实例方法将以前创建的NSNuber对象设置为指定的值,这些方法是以initWith开头,如initWithFloat。 NSNumber类有很多方法,几种常见用法如下: numberWith…:用初始值创建NSNumber对象,例如:numberWithInt:100; integerValue:获取NSNumber对象的值,其它如charValue,floatValue等; isEqualToNumber:比较两个NSNumber对象的数值是否相等,返回一个BOOL值。 compare:比较两个NSNumber对象数值的大小。返回结果有NSOrderedAscending,NSOrderedSame和NSOrderedDescending。 最近objective-c语言扩展允许通过@表达式创建数字对象。如果@之后的值是一个表达式或者变量需要使用括号。 #import <Foundation/Foundation.h> int main(int argc,const char * argv[]) { @autoreleasepool { NSNumber *myNumber,*floatNumber,*intNumber; intNumber=[NSNumber numberWithInt:100]; NSLog(@"%li",[intNumber integerValue]);//100 floatNumber=[NSNumber numberWithFloat:100.00]; NSLog(@"%f",[floatNumber floatValue]);//100.000000 myNumber=[NSNumber numberWithChar:'A']; NSLog(@"%c",[myNumber charValue]);//A //判断两个数字是否相等 if([intNumber isEqualToNumber:floatNumber]==YES) { NSLog(@"int number is equal to float number");//√ } else{ NSLog(@"int number is not equal to float number"); } //比较两个数字大小 if([intNumber compare:myNumber]==NSOrderedAscending) { NSLog(@"int number is less than mynumber"); } else{ NSLog(@"int number is more than mynumber");//√ } //@语法 intNumber=@200; NSLog(@"%li",[intNumber integerValue]);//200 } return 0; } 二 字符串 1.常量字符串对象 在字符串开头放一个@符号,就可以创建一个字符串常量对象。例如:@"Hello World!" 2.decription NSLog(@"%@",a)中,%@既可以显示NSString对象,也可以显示其它对象。通过覆盖description方法,可以自定义对象的显示格式。 Complex.h #import <Foundation/Foundation.h> @interface Complex : NSObject @property int real,imaginary; -(void)setReal:(int)r andImaginary:(int)m; @end Complex.m #import "Complex.h" @implementation Complex @synthesize real,imaginary; -(void)setReal:(int)r andImaginary:(int)m { self.real=r; self.imaginary=m; } //重写description,自定义输出格式 -(NSString *)description { return [NSString stringWithFormat:@"%i + %ii",self.real,self.imaginary]; } @end main.m #import <Foundation/Foundation.h> #import "Complex15.h" int main(int argc,const char * argv[]) { @autoreleasepool { Complex15 *c=[[Complex15 alloc] init]; [c setReal:1 andImaginary:2]; NSLog(@"%@",c);//由<Complex15: 0x10010ffa0> 变为 1 + 2i } return 0; } 2.不可变字符串NSString 注意:不可变字符串对象表明它所引用的字符串对象的字符不可改变,但是可以重新为它们指定为其它的不可变字符串对象。 NSString常用的方法: length:获取字符串长度; NSString stringWithString:复制字符串内容; stringByAppendingString:连接两个字符串; isEqualToString:比较两个字符串是否相等; compare:字符串比较,常用于排序。比较结果为NSOrderedAssending,NSOrderedSame或NSOrderedDescending。 uppercaseString:字符串转换为大写; lowercaseString:字符串转换为小写。 int main(int argc, const char * argv[]) { @autoreleasepool { NSString *str1=@"This is String A"; NSString *str2=@"This is String B"; NSString *result; NSComparisonResult compareResult; // 字符串长度 NSLog(@"length of str1 is %lu",[str1 length]);//length of str1 is 16 //复制字符串 result=[NSString stringWithString:str1]; NSLog(@"Copy str1,result is: %@",result);//Copy str1,result is: This is String A //追加字符串 str2=[str1 stringByAppendingString:str2]; NSLog(@"str1 append str2 is:%@",str2);//str1 append str2 is:This is String AThis is String B //字符串是否相等 if([str1 isEqualToString:result]){ NSLog(@"str1==result");//√ } else{ NSLog(@"str!=str2"); } //比较字符串 compareResult=[str1 compare:str2]; if(compareResult==NSOrderedAscending){ NSLog(@"str1<str2");//√ }else if(compareResult==NSOrderedSame){ NSLog(@"str1=str2"); }else{ NSLog(@"str1>str2"); } //大小写转换 result=[str1 uppercaseString]; NSLog(@"upper case:%@",result);//upper case:THIS IS STRING A result=[str1 lowercaseString]; NSLog(@"lower case:%@",result);//lower case:this is string a } return 0; } 子字符串操作: substringToIndex:返回一个子串,截取从开头到指定索引数的字符,但是不包括这个字符。 substringFromIndex:返回一个子串,截取从指定位置到字符串结尾的字符。 substringWithRange:返回指定范围的字符,参数是NSRange类型。 rangeOfString:在字符串中查找子串,返回结果是NSRange类型,它是一个结构变量,不是对象变量。返回结果range.location表示子串起始位置,range.length表示子串长度。如果找不到指定子串,则location为NSNotFound。 int main(int argc, const char * argv[]) { @autoreleasepool { NSString *str1=@"This is String A"; NSString *result; NSRange range; //从开头取前N个字符 result=[str1 substringToIndex:4]; NSLog(@"前4个字符:%@",result);//前4个字符:This //取第N个字符到结尾 result=[str1 substringFromIndex:8]; NSLog(@"后8个字符:%@",result);//后8个字符:String A //提取第8到13个字符 result=[[str1 substringFromIndex:8] substringToIndex:6]; NSLog(@"第8到13个字符:%@",result);//第8到13个字符:String //另一种实现方式 result=[str1 substringWithRange:NSMakeRange(8,6)]; NSLog(@"第8到13个字符:%@",result);//第8到13个字符:String //查找子串 range=[str1 rangeOfString:@"String"]; NSLog(@"String子串位置%lu,长度是%lu",range.location,range.length);//String子串位置8,长度是6 //查找不存在的子串 range=[str1 rangeOfString:@"StringA"]; if(range.location==NSNotFound){ NSLog(@"未找到子串StringA");//√ }else{ NSLog(@"子串StringA位置为%lu",range.location); } } } 3.可变字符串NSMutableString NSMutalbleString是NSString的子类,用来创建可以更改字符的字符串对象。 NSMutableString常用方法: insertString:atIndex :在指定位置插入字符串; appendString: 在字符串结尾插入字符串; deleteCharactersInRange:删除字符串中指定数目的字符。 setString:直接设置可变字符串对象的内容; int main(int argc, const char * argv[]) { @autoreleasepool { NSString *str=@"This is String A"; NSMutableString *mstr; NSRange substr; mstr=[NSMutableString stringWithString:str]; NSLog(@"%@",mstr);//This is String A //插入字符 [mstr insertString:@" mutable" atIndex:7]; NSLog(@"%@",mstr);//This is mutable String A //追加字符 [mstr appendString:@" and String B"]; NSLog(@"%@",mstr);//This is mutable String A and String B //删除子串 [mstr deleteCharactersInRange:NSMakeRange(16, 8)]; NSLog(@"%@",mstr);//This is mutable and String B //查找子串并删除 substr=[mstr rangeOfString:@"and String B"]; if(substr.location!=NSNotFound){ [mstr deleteCharactersInRange:substr]; NSLog(@"%@",mstr);//This is mutable } //直接设置可变字符串内容 [mstr setString:@"This is String."]; NSLog(@"%@",mstr);//This is String. //替换子串 [mstr replaceCharactersInRange:NSMakeRange(7, 1) withString:@" mutable "]; NSLog(@"%@",mstr);//This is mutable String. 本文转自 陈敬(Cathy) 博客园博客,原文链接:http://www.cnblogs.com/janes/p/5467215.html,如需转载请自行联系原作者

优秀的个人博客,低调大师

【转】IOS中截屏的实现,很简易的方法

#import <QuartzCore/QuartzCore.h> 添加QuartzCore.framework库 -(void) screenShot { UIGraphicsBeginImageContext(self.bounds.size); [self.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *image= UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); NSLog(@"image:%@",image); UIImageView *imaView = [[UIImageView alloc] initWithImage:image]; imaView.frame = CGRectMake(0, 700, 500, 500); [self addSubview:imaView]; [imaView release]; UIImageWriteToSavedPhotosAlbum(image, self, nil, nil); } 本文转自编程小翁博客园博客,原文链接:http://www.cnblogs.com/wengzilin/archive/2012/05/04/2482947.html,如需转载请自行联系原作者

优秀的个人博客,低调大师

iOS - 解决Unable to add a source with url `https://github.com/CocoaPods/...

[!] Unable to add a source with url `https://github.com/CocoaPods/Specs.git` named `master`. You can try adding it manually in `~/.cocoapods/repos` or via `pod repo add`. 1 2 解决方案: pod repo add master https://github.com/CocoaPods/Specs.git 1 然后提示执行’pod setup’,如果出现 [!] The `master` repo is not a git repo. 1 进入/users/你的用户名/.cocoapods/repos,删除master文件夹 然后执行 pod setup 如果pod setup 不顺利采用:Git clonehttps://git.coding.net/CocoaPods/Specs.git~/.cocoapods/repos/master 该过程作用与 pod setup作用相同 1 如果是安装多个Xcdoe,还需要选择Xcode的路径 sudo xcode-select -switch /Applications/Xcode.app/ 1 在终端里输入下方命令可以知道Xcode的路径: xcode-select -p 2: --------------------------------------------- 问题:cocoapods was not able to update the 'master' repo.if it is a unexpected issue and persists you can inspect it running 'pod repo update --verbose' 尝试解决: 尝试1、根据提示,跑一下 pod repo update --verbose 尝试2、如果还是出现原来问题,升级 gem update cocoapods(如果CocoaPods还不是最新版本) 尝试3、如果升级还是出现原来的问题,那么重装CocoaPods 。 首先查看本地装了关于cocoapods的哪些东西,在终端输入gem list --local | grep cocoapods 接着全部卸掉上面的,在终端输入gem uninstall cocoapods 再安装,在终端输入gem install cocoapods 尝试4、如果问题依旧,那么请清除缓存再pod setup 清除命令sudo rm -fr ~/.cocoapods/repos/master 再pod setup 3 安装 pod 报错-------------------------------- ERROR: While executing gem ... (OpenSSL::SSL::SSLError) 原创 2015年07月14日 23:11:37 标签: openssl 5448 方法一: 1) outdate open SSL $ rvm -v $ rvm get head 2) outdate bundle $ gem install bundle 方法二: $ gem update --system 方法三: $ apt-get install openssl

优秀的个人博客,低调大师

iOS 实战之将 deviceToken 转换成字符串

方式1 - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { NSMutableString *deviceTokenString1 = [NSMutableStringstring]; const char *bytes = deviceToken.bytes; int iCount = deviceToken.length; for (int i = 0; i < iCount; i++) { [deviceTokenString1 appendFormat:@"%02x", bytes[i]&0x000000FF]; } NSLog(@"方式1:%@", deviceTokenString1); } 方式2 - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { NSString *deviceTokenString2 = [[[[deviceTokendescription] stringByReplacingOccurrencesOfString:@"<"withString:@""] stringByReplacingOccurrencesOfString:@">" withString:@""] stringByReplacingOccurrencesOfString:@" " withString:@""]; NSLog(@"方式2:%@", deviceTokenString2); }

优秀的个人博客,低调大师

iOS: 使用KVO监听控制器中数组的变化

一、介绍: KVO是一种能动态监听到属性值的改变的方式,使用场景非常广泛,这里我只讲如何监听控制器ViewController中数组的变化。 二、了解: 首先我们应该知道KVO是不能直接监听控制器ViewController数组的变化的,需要将数组定义在模型中,然后控制器ViewController持有模型对象,通过该对象才能监听。 三、步骤: <1>在控制器ViewController类中定义一个模型类Model,并在该类中声明一个可变的数组属性modelArray并进行懒加载,其实它最终就是作为控制器ViewController的数组使用; #import <UIKit/UIKit.h> @interface ViewController : UIViewController @end /** * 在控制器新定义一个模型类 */ @interface Model : NSObject /** * 可变的数组 */ @property (strong,nonatomic)NSMutableArray *modelArray; @end #import "ViewController.h" @implementation ViewController @end @implementation Model /** * 懒加载 */ -(NSMutableArray *)modelArray{ if(!_modelArray){ _modelArray = [NSMutableArray array]; } return _modelArray; } @end <2>在控制器ViewController中持有模型类Model的全局对象; #import "ViewController.h" @interface ViewController () /** * 持有模型对象 */ @property (strong,nonatomic)Model *model; @end <3>用第2步创建的对象注册监听,监听属性就是数组modelArray,即modelArray作为keyPath值,注册方法为; - (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(nullable void *)context; //注册KVO监听 [_model addObserver:self forKeyPath:@"modelArray" options:NSKeyValueObservingOptionNew context:nil]; <4>重写监听方法,监听值的变化; - (void)observeValueForKeyPath:(nullable NSString *)keyPath ofObject:(nullable id)object change:(nullable NSDictionary<NSString*, id> *)change context:(nullable void *)context; //重写监听方法 -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{ if ([keyPath isEqualToString:@"modelArray"]) { NSLog(@"%ld",_model.modelArray.count); } } <5>移除监听,最后释放内内存时需要把监听移除掉 -(void)dealloc{ [_model removeObserver:self forKeyPath:@"modelArray"]; } <6>点击界面,模拟数据添加到数组中,添加方法必须是:- (NSMutableArray *)mutableArrayValueForKeyPath:(NSString *)keyPath; -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ NSObject *obj = [[NSObject alloc]init]; [[_model mutableArrayValueForKeyPath:@"modelArray"] addObject:obj]; } 四、演示截图:(每点击一次,能够监听到数组个数增加1) 五、完整代码如下: .h文件 // // ViewController.h // KVOTest // // Created by 夏远全 on 16/11/23. // Copyright © 2016年 广州市东德网络科技有限公司. All rights reserved. // #import <UIKit/UIKit.h> @interface ViewController : UIViewController @end /** * 在控制器新定义一个模型类 */ @interface Model : NSObject /** * 可变的数组 */ @property (strong,nonatomic)NSMutableArray *modelArray; @end .m文件 // // ViewController.m // KVOTest // // Created by 夏远全 on 16/11/23. // Copyright © 2016年 广州市东德网络科技有限公司. All rights reserved. // #import "ViewController.h" @interface ViewController () /** * 持有模型对象 */ @property (strong,nonatomic)Model *model; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; //1.创建模型对象 _model = [[Model alloc]init]; //2.注册KVO监听 [_model addObserver:self forKeyPath:@"modelArray" options:NSKeyValueObservingOptionNew context:nil]; } /** * 3.重写监听方法 */ -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{ if ([keyPath isEqualToString:@"modelArray"]) { NSLog(@"%ld",_model.modelArray.count); } } /** * 4.移除监听 */ -(void)dealloc{ [_model removeObserver:self forKeyPath:@"modelArray"]; } /** * 5.模拟往数组添加数据 */ -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ NSObject *obj = [[NSObject alloc]init]; [[_model mutableArrayValueForKeyPath:@"modelArray"] addObject:obj]; } @end @implementation Model /** * 懒加载 */ -(NSMutableArray *)modelArray{ if(!_modelArray){ _modelArray = [NSMutableArray array]; } return _modelArray; } @end 注明:本人原创,牛人可以路过,希望可以帮到小白,嘿嘿 欢迎关注github:https://github.com/xiayuanquan 程序猿神奇的手,每时每刻,这双手都在改变着世界的交互方式! 本文转自当天真遇到现实博客园博客,原文链接:http://www.cnblogs.com/XYQ-208910/p/6096186.html ,如需转载请自行联系原作者

优秀的个人博客,低调大师

iOS:步进UIStepper、滑动块UISlider、开关UISwitch的基本使用

步进UIStepper、滑动块UISlider:当它们作为事件,被触发时,它们的值会发生改变。正因为如此,触发该事件时,可以一张一张翻阅浏览图片,,,, 步进UIStepper: @property(nonatomic) double minimumValue; // default 0. must be less than maximumValue @property(nonatomic) double maximumValue; // default 100. must be greater than minimumValue @property(nonatomic) double stepValue; // default 1. must be greater than 0,每次步进的距离 1 //滑动块触发事件(值value发生改变,范围mininum~maxnum) 2 - (IBAction)sliderValueChange:(UISlider *)sender 3 { 4 NSLog(@"%lf",sender.value); 5 //将滑动块的值取出并赋给步进,使得步进和滑动块事件状态相同 6 [self.stepper setValue:sender.value]; 7 } 滑动块UIStepper: @property(nonatomic) float value; // default 0.0. this value will be pinned to min/max @property(nonatomic) float minimumValue; // default 0.0. the current value may change if outside new min value @property(nonatomic) float maximumValue; // default 1.0. the current value may change if outside new max value 1 //步进触发事件(值value发生改变,范围mininum~maxnum,可以设置步进大小step值) 2 - (IBAction)stepperValueChange:(UIStepper *)sender 3 { 4 NSLog(@"%lf",sender.value); 5 //将步进的值取出并赋给滑动块,使得步进和滑动块事件状态相同 6 [self.slider setValue:sender.value]; 7 } 开关UISwitch: @property(nonatomic,getter=isOn) BOOL on; //有两种状态,开on或关off 1 //开关触发事件(状态state只有两种形式:on、off) 2 - (IBAction)switchValueChange:(UISwitch *)sender 3 { 4 NSLog(@"%@",sender.isOn?@"开":@"关"); 5 } 以下用步进和滑动块、开关做的一个图片浏览器 源码如下: 1 // ViewController.m 2 // 02-图片浏览器 3 // 4 // Created by ma c on 15/8/27. 5 // Copyright (c) 2015年 bjsxt. All rights reserved. 6 // 7 8 #import "ViewController.h" 9 10 @interface ViewController () 11 @property (weak, nonatomic) IBOutlet UILabel *labelTitle; 12 @property (weak, nonatomic) IBOutlet UILabel *labelInfo; 13 @property (weak, nonatomic) IBOutlet UIImageView *imageView; 14 @property (weak, nonatomic) IBOutlet UIStepper *stepper; 15 @property (weak, nonatomic) IBOutlet UISlider *slider; 16 @property (strong,nonatomic) NSArray *imageInfos; 17 @property (assign,nonatomic) NSInteger index;//显示当前图片的索引 18 @property (assign,nonatomic) NSInteger total;//图片的个数 19 @end 20 21 @implementation ViewController 22 - (IBAction)stepperValueChange:(UIStepper *)sender 23 { 24 [self.slider setValue:sender.value]; 25 self.index = [self.stepper value]; 26 [self setImageIndex:self.index]; 27 } 28 - (IBAction)sliderValueChange:(UISlider *)sender 29 { 30 [self.stepper setValue:sender.value]; 31 self.index = [self.slider value]; 32 [self setImageIndex:self.index]; 33 } 34 35 - (void)viewDidLoad { 36 [super viewDidLoad]; 37 //加载图片信息 38 NSString *path = [[NSBundle mainBundle] pathForResource:@"images" ofType:@"plist"]; 39 self.imageInfos = [NSArray arrayWithContentsOfFile:path]; 40 41 42 //初始化 43 self.total = [self.imageInfos count]; 44 self.index = 0; 45 46 self.stepper.minimumValue = 0; 47 self.stepper.maximumValue = self.total - 1; 48 self.stepper.value = 0; 49 self.stepper.stepValue = 1; 50 51 self.slider.minimumValue = 0; 52 self.slider.maximumValue = self.total - 1; 53 self.slider.value = 0; 54 55 56 self.imageView.contentMode = UIViewContentModeScaleAspectFit; 57 [self setImageIndex:0]; 58 59 } 60 61 -(void)setImageIndex:(NSUInteger)index 62 { 63 64 //取出数组中的字典 65 NSDictionary *dicImage = self.imageInfos[index]; 66 NSString *imageName = [dicImage objectForKey:@"icon"]; 67 NSString *imageTitle = [dicImage objectForKey:@"title"]; 68 69 //设置显示的图片 70 self.imageView.image = [UIImage imageNamed:imageName]; 71 72 //设置显示的图片的标题 73 self.labelTitle.text = imageTitle; 74 75 //设置当前信息:索引/总数 76 self.labelInfo.text = [NSString stringWithFormat:@"%ld/%ld",self.index+1,self.total]; 77 } 78 79 - (void)didReceiveMemoryWarning { 80 [super didReceiveMemoryWarning]; 81 // Dispose of any resources that can be recreated. 82 } 83 84 @end 程序猿神奇的手,每时每刻,这双手都在改变着世界的交互方式! 本文转自当天真遇到现实博客园博客,原文链接:http://www.cnblogs.com/XYQ-208910/p/4764382.html,如需转载请自行联系原作者

优秀的个人博客,低调大师

iOS:UICollectionView纯自定义的布局:瀑布流布局

创建瀑布流有三种方式: 第一种方式:在一个ScrollView里面放入三个单元格高度一样的tableView,禁止tableView滚动,只需让tableView随着ScrollView滚动即可。这种方式太奇葩,不太推荐使用... 第二种方式:在一个ScrollView里面从左到右依次放入三个UIView,当ScrollView滚动时,如果之前的三个view消失就将它们存入自定义的缓冲池,即数组中,下拉时再从数组中取出这三个view放到之前三个view位置的下面。但是,切记,每次要依次计算补全最短的,防止拉开的间距越来越大...,这种方式稍微麻烦一些… 第三种方式:其实就是上面第二种的简单版,就是使用UICollectionView,因为它有自己的重用机制,我们只需要做的就是计算下一次cell的位置即可.... 集合视图的自动布局:UICollectionViewLayout是抽象根类,必须用它的子类才能创建实例,下面是重写的方法,计算item的布局属性 //每一次重新布局前,都会准备布局(苹果官方推荐使用该方法进行一些初始化) -(void)prepareLayout //重写layoutAttributesForItemAtIndexPath,返回每一个item的布局属性(流式布局内部已经帮助完成) -(UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath //是否要重新刷新布局(只要显示的item边界发生改变就重新布局) //只要每一次重新布局内部就会调用下面的layoutAttributesForElementsInRect:获取所有cell(item)的属性 -(BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds //返回需要重新布局的所有item属性 -(NSArray*)layoutAttributesForElementsInRect:(CGRect)rect :下面的瀑布流布局可以直接拿走使用 下面使用第三种方式创建的瀑布流代码如下: WaterFlowLayout.h #import <UIKit/UIKit.h> /* 为了体现封装性的特点,我们可以把一些数据设置为公共的,既可以提高扩展性和通用性, 也便于外界按照自己的需求做必要的调整。 */ @protocol WaterFlowLayoutDelegate; //设置代理传递数据,降低了与其他类的耦合性,通用性更强 @class WaterFlowLayout; @interface WaterFlowLayout : UICollectionViewLayout @property (assign,nonatomic)CGFloat columnMargin;//每一列item之间的间距 @property (assign,nonatomic)CGFloat rowMargin; //每一行item之间的间距 @property (assign,nonatomic)UIEdgeInsets sectionInset;//设置于collectionView边缘的间距 @property (assign,nonatomic)NSInteger columnCount;//设置每一行排列的个数 @property (weak,nonatomic)id<WaterFlowLayoutDelegate> delegate; //设置代理 @end @protocol WaterFlowLayoutDelegate -(CGFloat)waterFlowLayout:(WaterFlowLayout *) WaterFlowLayout heightForWidth:(CGFloat)width andIndexPath:(NSIndexPath *)indexPath; @end WaterFloeLayout.m #import "WaterFlowLayout.h" //每一列item之间的间距 //static const CGFloat columnMargin = 10; //每一行item之间的间距 //static const CGFloat rowMargin = 10; @interface WaterFlowLayout() /** 这个字典用来存储每一列item的高度 */ @property (strong,nonatomic)NSMutableDictionary *maxYDic; /** 存放每一个item的布局属性 */ @property (strong,nonatomic)NSMutableArray *attrsArray; @end @implementation WaterFlowLayout /** 懒加载 */ -(NSMutableDictionary *)maxYDic { if (!_maxYDic) { _maxYDic = [NSMutableDictionary dictionary]; } return _maxYDic; } /** 懒加载 */ -(NSMutableArray *)attrsArray { if (!_attrsArray) { _attrsArray = [NSMutableArray array]; } return _attrsArray; } //初始化 -(instancetype)init { if (self = [super init]){ self.columnMargin = 10; self.rowMargin = 10; self.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10); self.columnCount = 3; } return self; } //每一次布局前的准备工作 -(void)prepareLayout { [super prepareLayout]; //清空最大的y值 for (int i =0; i < self.columnCount; i++) { NSString *column = [NSString stringWithFormat:@"%d",i]; self.maxYDic[column] = @(self.sectionInset.top); } //计算所有item的属性 [self.attrsArray removeAllObjects]; NSInteger count = [self.collectionView numberOfItemsInSection:0]; for (int i=0; i<count; i++) { UICollectionViewLayoutAttributes *attrs = [self layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForItem:i inSection:0]]; [self.attrsArray addObject:attrs]; } } //设置collectionView滚动区域 -(CGSize)collectionViewContentSize { //假设最长的那一列为第0列 __block NSString *maxColumn = @"0"; //遍历字典,找出最长的那一列 [self.maxYDic enumerateKeysAndObjectsUsingBlock:^(NSString *column, NSNumber *maxY, BOOL *stop) { if ([maxY floatValue] > [self.maxYDic[maxColumn] floatValue]) { maxColumn = column; } }]; return CGSizeMake(0, [self.maxYDic[maxColumn]floatValue]+self.sectionInset.bottom); } //允许每一次重新布局 -(BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds { return YES; } //布局每一个属性 -(UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath { //假设最短的那一列为第0列 __block NSString *minColumn = @"0"; //遍历字典,找出最短的那一列 [self.maxYDic enumerateKeysAndObjectsUsingBlock:^(NSString *column, NSNumber *maxY, BOOL *stop) { if ([maxY floatValue] < [self.maxYDic[minColumn] floatValue]) { minColumn = column; } }]; //计算每一个item的宽度和高度 CGFloat width = (self.collectionView.frame.size.width - self.columnMargin*(self.columnCount - 1) - self.sectionInset.left - self.sectionInset.right) / self.columnCount; CGFloat height = [self.delegate waterFlowLayout:self heightForWidth:width andIndexPath:indexPath] ; //计算每一个item的位置 CGFloat x = self.sectionInset.left + (width + self.columnMargin) * [minColumn floatValue]; CGFloat y = [self.maxYDic[minColumn] floatValue] + self.rowMargin; //更新这一列的y值 self.maxYDic[minColumn] = @(y + height); //创建布局属性 UICollectionViewLayoutAttributes *attrs = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath]; //设置item的frame attrs.frame = CGRectMake(x, y, width, height); return attrs; } //布局所有item的属性,包括header、footer -(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect { return self.attrsArray; } @end 瀑布流演示结果如下: github:https://github.com/xiayuanquan/XYQCollectionLayout.git 程序猿神奇的手,每时每刻,这双手都在改变着世界的交互方式! 本文转自当天真遇到现实博客园博客,原文链接:http://www.cnblogs.com/XYQ-208910/p/4985560.html如需转载请自行联系原作者

资源下载

更多资源
Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

Sublime Text

Sublime Text

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。

用户登录
用户注册
修改密码
忘记密码