IOS6新特性之集合视图UICollectionView介绍
- 格式:doc
- 大小:28.50 KB
- 文档页数:3
标签collectionview简书UICollectionView是iOS开发中常用的控件之一,它能够以表格或瀑布流的形式展示多个item,并支持自定义的cell。
在实际开发中,我们常常需要对这些item进行分类,这时候标签就派上用场了。
在UICollectionView中使用标签,通常是通过UICollectionViewFlowLayout来实现的。
我们可以将标签作为一种特殊的cell类型,然后在UICollectionViewDelegateFlowLayout协议的方法中,对标签的布局进行定制。
具体实现可以参考以下代码: ```swiftclass TagCollectionViewCell: UICollectionViewCell {// 标签的样式和显示内容}class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {var tags: [String] = []// 标签数据源override func viewDidLoad() {super.viewDidLoad()let layout = UICollectionViewFlowLayout()layout.scrollDirection = .verticallayout.minimumLineSpacing = 10layout.minimumInteritemSpacing = 10// 设置布局属性,包括滚动方向、行间距、列间距等let collectionView = UICollectionView(fra .zero, collectionViewLayout: layout)collectionView.delegate = selfcollectionView.dataSource = self// 初始化collectionViewcollectionView.register(TagCollectionViewCell.self, forCellWithReuseIdentifier: 'TagCollectionViewCell')// 注册标签cell类型view.addSubview(collectionView)// 将collectionView添加到当前视图中}// 下面是UICollectionViewDelegateFlowLayout协议的实现 func collectionView(_ collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {let text = tags[indexPath.row]let size = text.size(withAttributes: [.font:UIFont.systemFont(ofSize: 14)])return CGSize(width: size.width + 20, height: size.height + 10)// 根据标签的内容自适应大小}func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {return UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)// 设置collectionView的边距}// 下面是UICollectionViewDelegate和UICollectionViewDataSource协议的实现}```除了布局定制之外,我们还可以为标签cell添加点击事件,以便在用户点击标签时进行相应的操作。
ios.--UICollectionView--cell⾃适应#pragma mark — 视图控制器中使⽤:(关键)layout.estimatedItemSize = CGSizeMake(WIDTH, 60); // layout约束这边必须要⽤estimatedItemSize才能实现⾃适应,使⽤itemSzie⽆效//// 商品详情容器详情 cell#import <UIKit/UIKit.h>@interface DetailsViewCell : UICollectionViewCell@property (nonatomic,strong) CategorizeListOfGoodsModel *goodsitemmodel;@end#import"DetailsViewCell.h"@interface DetailsViewCell()@property (nonatomic,strong) UILabel *titletxt;//标题@property (nonatomic,strong) UILabel *pracetxt;//价格@property (nonatomic,strong) UILabel *msaletxt;//销量@end@implementation DetailsViewCell- (void)setGoodsitemmodel:(CategorizeListOfGoodsModel *)goodsitemmodel{_goodsitemmodel = goodsitemmodel;self.titletxt.text = [NSString stringWithFormat:@"%@",goodsitemmodel.title];self.pracetxt.text = [NSString stringWithFormat:@"¥%@",goodsitemmodel.voucher_price];self.msaletxt.text = [NSString stringWithFormat:@"⽉销%@",goodsitemmodel.m_sale];[self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {make.left.top.mas_equalTo(0);make.width.mas_equalTo([UIScreen mainScreen].bounds.size.width);make.bottom.mas_equalTo(self.pracetxt.mas_bottom).offset(10);}];[self.titletxt mas_makeConstraints:^(MASConstraintMaker *make) {make.top.equalTo(self).mas_offset(10);make.left.equalTo(self).mas_offset(10);make.right.equalTo(self).mas_offset(-10);}];[self.pracetxt mas_makeConstraints:^(MASConstraintMaker *make) {make.top.equalTo(self.titletxt.mas_bottom).mas_offset(10);make.bottom.equalTo(self).mas_offset(-10);make.left.equalTo(self).mas_offset(10);}];[self.msaletxt mas_makeConstraints:^(MASConstraintMaker *make) {make.top.equalTo(self.titletxt.mas_bottom).mas_offset(10);make.bottom.equalTo(self).mas_offset(-10);make.right.equalTo(self).mas_offset(-10);}];}- (instancetype)initWithFrame:(CGRect)frame{if (self = [super initWithFrame:frame]) {[self initWithUIFrame:frame];}return self;}- (void)initWithUIFrame:(CGRect)rect{self.contentView.backgroundColor = [UIColor whiteColor];self.titletxt = [[UILabel alloc]init];self.titletxt.font = [UIFont systemFontOfSize:14];self.titletxt.textColor = [YColor YColorWithHexString:@"#333333"];self.titletxt.numberOfLines = 0;[self.contentView addSubview:self.titletxt];self.pracetxt = [[UILabel alloc]init];self.pracetxt.font = [UIFont systemFontOfSize:16];self.pracetxt.textColor = [YColor YColorWithHexString:@"#F32F19"];[self.contentView addSubview:self.pracetxt];self.msaletxt = [[UILabel alloc]init];self.msaletxt.font = [UIFont systemFontOfSize:12];self.msaletxt.textColor = [YColor YColorWithHexString:@"#999999"];[self.contentView addSubview:self.msaletxt];}#pragma mark — 实现⾃适应⽂字宽度的关键步骤:item的layoutAttributes- (UICollectionViewLayoutAttributes*)preferredLayoutAttributesFittingAttributes:(UICollectionViewLayoutAttributes*)layoutAttributes { [self setNeedsLayout];[self layoutIfNeeded];CGSize size = [self.contentView systemLayoutSizeFittingSize: layoutAttributes.size];CGRect cellFrame = layoutAttributes.frame;cellFrame.size.height= size.height;layoutAttributes.frame= cellFrame;return layoutAttributes;}@end。
iOS-UICollectionView基本使⽤UICollectionViewUICollectionView基于UIScrollView,系统默认内容⾃动偏移64各单位,所以可以通过设置以下设置取消偏移self.automaticallyAdjustsScrollViewInsets = NO;UICollectionView必须设置瀑布流UICollectionViewFlowLayout,如:UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];layout.minimumLineSpacing = 5.0;layout.minimumInteritemSpacing = 5.0;layout.sectionInset = UIEdgeInsetsMake(5.0, 5.0, 5.0, 5.0);UICollectionView必须设置数据源和代理,如:_mineCollection = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 64.0,DEVICE_WIDTH, DEVICE_HEIGHT - 64.0) collectionViewLayout:layout];_mineCollection.backgroundColor = [UIColor lightGrayColor];_mineCollection.dataSource = self;_mineCollection.delegate = self;cell必须通过注册,如:[_mineCollection registerClass:[MineCollectionViewCell class]forCellWithReuseIdentifier:collectionCell];[_mineCollection registerClass:[CollectionReusableView class]forSupplementaryViewOfKind:UICollectionElementKindSectionHeaderwithReuseIdentifier:collectionHeader];cell必须⾃定义,系统cell没有任何⼦控件UICollectionView必须设置数据源和代理//分区,组- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView*)collectionView//每⼀分区的单元个数- (NSInteger)collectionView:(UICollectionView *)collectionViewnumberOfItemsInSection:(NSInteger)section//集合视图单元格⼤⼩- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath//头部⼤⼩- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayoutreferenceSizeForHeaderInSection:(NSInteger)section//集合视图头部或者尾部- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath//单元格复⽤- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionViewcellForItemAtIndexPath:(NSIndexPath *)indexPath//被选中的单元格- (void)collectionView:(UICollectionView *)collectionViewdidSelectItemAtIndexPath:(NSIndexPath *)indexPathUICollectionViewFlowLayout初始化layout后⾃动调动,可以在该⽅法中初始化⼀些⾃定义的变量参数* Invalidate:刷新,在滚动的时候是否允许刷新布局-(BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {return YES;}* 设置UICollectionView的内容⼤⼩,道理与UIScrollView的contentSize类似,@return 返回设置的UICollectionView的内容⼤⼩-(CGSize)collectionViewContentSize* 初始Layout外观 @param rect 所有元素的布局属性 @return 所有元素的布局-(NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect: (CGRect)rect* 根据不同的indexPath,给出布局 @param indexPath @return 布局-(UICollectionViewLayoutAttributes )layoutAttributesForItemAtIndexPath: (NSIndexPath)indexPath```demo。
uicollectionview cell的事件-回复UICollectionView是iOS开发中常用的视图控件,用于展示一个可滚动的列表,类似于UITableView。
相比于UITableView,UICollectionView 提供了更灵活的布局和更多的交互方式。
在UICollectionView中,每个元素通常被称为一个"cell"。
这篇文章将重点介绍如何在UICollectionView中处理cell的事件。
第一步:创建UICollectionView首先,我们需要创建一个UICollectionView。
在Interface Builder中,可以直接拖拽一个UICollectionView到界面上。
也可以通过代码创建:UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout]; collectionView.dataSource = self;collectionView.delegate = self;[self.view addSubview:collectionView];上述代码中,我们创建了一个UICollectionViewFlowLayout来指定collectionView的布局。
然后创建了一个UICollectionView,并设置了数据源和代理为当前的ViewController。
最后,将collectionView添加到当前的视图中。
第二步:实现数据源方法UICollectionView需要一个数据源来提供展示的数据。
今天给大家分享下自己在家写的后台框架,实现功能模仿SSH,iOS UICollectionView基本属性和代理方法... ,iOS UIImage改变图片的背景色改成纯色iOS UITableView基本属性函数用法...[代码] [Java]代码// ("starts to initialize context..!!");("stats to scan reqmapping..");try {if (resolver) {ResolveGateWay.create(ConfigLoader.getInstance().getValue("reqmapping")).delega tion();}// IOC..if (ioc) {AppContext context = new ClassPathAppContext();context.inital();}} catch (Exception e) {logger.error("包扫描异常...", e);}// 初始化数据库连接池if (initalDataSourcePool) {DataSourceFacade.getInstance();}代码写的不当的地方请指教。
希望大家共同进步学习.本人工作4年,主做Java,目前在北京catch (IOException e) {System.err.println(e.getMessage());}}/*** 得到本关地图*/protected static void getMap() {try (BufferedReader br = new BufferedReader(new FileReader(newFile("./src/com/yuanhonglong/newTankWar/map/"+ TankWar.allMapPaths.get(0))))) {String string;for (int i = 0; i < MainFrame.FRAME_BUTTON_LINE; i++) {string = br.readLine();for (int j = 0; j < MainFrame.FRAME_BUTTON_COLUMN; j++) {TankWar.map[i][j] = string.charAt(j) - 48;}}TankWar.allMapPaths.remove(0);}catch (IOException e1) {System.err.println(e1.getMessage());}}/*** 本关初始化坦克*/protected static void tankInit() {for (int i = 0; i < MainFrame.FRAME_BUTTON_LINE; i++) {for (int j = 0; j < MainFrame.FRAME_BUTTON_COLUMN; j++) { if (TankWar.map[i][j] == 2) {TankWar.tankNumber++;final Tank tank = new Tank(((i + j) % 4) + 1);tank.line = i;tank.column = j;tank.lifes = TankWar.tankLife;tank.shootTask = new TimerTask() {@Overridepublic void run() {puterShoot();}};tank.goTask = new TimerTask() {@Overridepublic void run() {tank.go();}};TankWar.tanks.add(tank);}else if (TankWar.map[i][j] == 3) {TankWar.playerTank = new Tank(1);TankWar.playerTank.lifes = TankWar.tankLife;TankWar.playerTank.line = i;TankWar.playerTank.column = j;}else if (TankWar.map[i][j] == 6) {TankWar.kingTank = new Tank(1);TankWar.kingTank.lifes = 1;TankWar.kingTank.line = i;TankWar.kingTank.column = j;}[代码] [Google Go]代码package mainimport ("io/ioutil""net/http""net/""fmt""encoding/json")//----------------------------------// 黄金数据调用示例代码-聚合数据// 在线接口文档:www/docs/29//----------------------------------const APPKEY = "*******************" //您申请的APPKEYfunc main(){//1.上海黄金交易所Request1()//2.上海期货交易所Request2()//3.银行账户黄金Request3()}//1.上海黄金交易所func Request1(){//请求地址juhe :="web:8080/finance/gold/shgold"//初始化参数param:=.Values{}//配置请求参数,方法内部已处理encode问题,中文参数可以直接传参 param.Set("key",APPKEY) //APP Keyparam.Set("v","") //JSON格式版本(0或1)默认为0//发送请求data,err:=Get(juhe,param)if err!=nil{fmt.Errorf("请求失败,错误信息:\r\n%v",err)}else{var netReturn map[string]interface{}json.Unmarshal(data,&netReturn)if netReturn["error_code"].(float64)==0{fmt.Printf("接口返回result字段是:\r\n%v",netReturn["result"]) }}}//2.上海期货交易所func Request2(){//请求地址juhe :="web:8080/finance/gold/shfuture"//初始化参数param:=.Values{}//配置请求参数,方法内部已处理encode问题,中文参数可以直接传参param.Set("key",APPKEY) //APP Keyparam.Set("v","") //JSON格式版本(0或1)默认为0//发送请求data,err:=Get(juhe,param)if err!=nil{fmt.Errorf("请求失败,错误信息:\r\n%v",err)}else{var netReturn map[string]interface{}json.Unmarshal(data,&netReturn)if netReturn["error_code"].(float64)==0{fmt.Printf("接口返回result字段是:\r\n%v",netReturn["result"]) }}}//3.银行账户黄金func Request3(){//请求地址juhe :="web:8080/finance/gold/bankgold"//初始化参数param:=.Values{}//配置请求参数,方法内部已处理encode问题,中文参数可以直接传参param.Set("key",APPKEY) //APP Key//发送请求data,err:=Get(juhe,param)if err!=nil{fmt.Errorf("请求失败,错误信息:\r\n%v",err)}else{var netReturn map[string]interface{}json.Unmarshal(data,&netReturn)if netReturn["error_code"].(float64)==0{fmt.Printf("接口返回result字段是:\r\n%v",netReturn["result"]) }}}// get 网络请求func Get(api string,params .Values)(rs[]byte ,err error){var *.,err=.Parse(api)if err!=nil{fmt.Printf("解析错误:\r\n%v",err)return nil,err}//如果参数中有中文参数,这个方法会进行Encode.RawQuery=params.Encode()resp,err:=http.Get(.String())if err!=nil{fmt.Println("err:",err)return nil,err}defer resp.Body.Close()return ioutil.ReadAll(resp.Body)}// post 网络请求 ,params 是.Values类型func Post(api string, params .Values)(rs[]byte,err error){resp,err:=http.PostForm(api, params)if err!=nil{return nil ,err}defer resp.Body.Close()return ioutil.ReadAll(resp.Body)}代码描述:基于GO的黄金数据接口调用代码实例关联数据:黄金数据[代码] [C#]代码using System;using System.Collections.Generic;using System.Linq;using System.Text;using ;using System.IO;using ;using System.Diagnostics;using System.Web;//----------------------------------// 黄金数据调用示例代码-聚合数据// 在线接口文档:www/docs/29// 代码中JsonObject类下载地址:/download/gcm3206021155665/7458439//----------------------------------namespace ConsoleAPI{class Program{static void Main(string[] args){string appkey = "*******************"; //配置您申请的appkey//1.上海黄金交易所string 1 = "web:8080/finance/gold/shgold";var parameters1 = new Dictionary<string, string>();parameters1.Add("key", appkey);//你申请的keyparameters1.Add("v" , ""); //JSON格式版本(0或1)默认为0string result1 = sendPost(1, parameters1, "get");JsonObject newObj1 = new JsonObject(result1);String errorCode1 = newObj1["error_code"].Value;if (errorCode1 == "0"){Debug.WriteLine("成功");Debug.WriteLine(newObj1);}else{//Debug.WriteLine("失败");Debug.WriteLine(newObj1["error_code"].Value+":"+newObj1["reason"].Value); }//2.上海期货交易所string 2 = "web:8080/finance/gold/shfuture";var parameters2 = new Dictionary<string, string>();parameters2.Add("key", appkey);//你申请的keyparameters2.Add("v" , ""); //JSON格式版本(0或1)默认为0string result2 = sendPost(2, parameters2, "get");JsonObject newObj2 = new JsonObject(result2);String errorCode2 = newObj2["error_code"].Value;if (errorCode2 == "0"){Debug.WriteLine("成功");Debug.WriteLine(newObj2);}else{//Debug.WriteLine("失败");Debug.WriteLine(newObj2["error_code"].Value+":"+newObj2["reason"].Value); }//3.银行账户黄金string 3 = "web:8080/finance/gold/bankgold";var parameters3 = new Dictionary<string, string>();parameters3.Add("key", appkey);//你申请的keystring result3 = sendPost(3, parameters3, "get");JsonObject newObj3 = new JsonObject(result3);String errorCode3 = newObj3["error_code"].Value;if (errorCode3 == "0"){Debug.WriteLine("成功");Debug.WriteLine(newObj3);}else{//Debug.WriteLine("失败");Debug.WriteLine(newObj3["error_code"].Value+":"+newObj3["reason"].Value);}}/// <summary>/// Http (GET/POST)/// </summary>/// <param name="">请求</param>/// <param name="parameters">请求参数</param>/// <param name="method">请求方法</param>/// <returns>响应内容</returns>static string sendPost(string , IDictionary<string, string> parameters, string method){if (method.ToLower() == "post"){HttpWebRequest req = null;HttpWebResponse rsp = null;System.IO.Stream reqStream = null;try{req = (HttpWebRequest)WebRequest.Create();req.Method = method;req.KeepAlive = false;req.ProtocolVersion = HttpVersion.Version10;req.Timeout = 5000;req.ContentType ="application/x-www-form-encoded;charset=utf-8";byte[] postData =Encoding.UTF8.GetBytes(BuildQuery(parameters, "utf8"));reqStream = req.GetRequestStream();reqStream.Write(postData, 0, postData.Length);rsp = (HttpWebResponse)req.GetResponse();Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet); return GetResponseAsString(rsp, encoding);}catch (Exception ex){return ex.Message;}finally{if (reqStream != null) reqStream.Close();if (rsp != null) rsp.Close();}}else{//创建请求HttpWebRequest request = (HttpWebRequest)WebRequest.Create( + "?" + BuildQuery(parameters, "utf8"));//GET请求request.Method = "GET";request.ReadWriteTimeout = 5000;request.ContentType = "text/html;charset=UTF-8";HttpWebResponse response =(HttpWebResponse)request.GetResponse();Stream myResponseStream = response.GetResponseStream();StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));//返回内容string retString = myStreamReader.ReadToEnd();return retString;}}/// <summary>/// 组装普通文本请求参数。
关于Swift中UICollectionView的用法在iOS开发中,UICollectionView是一个非常强大和灵活的工具,用于展示和管理大量的数据。
它能够以网格形式展示数据,并支持各种自定义布局和样式。
在Swift中,我们可以通过UICollectionView实现各种复杂和炫目的界面,同时也能够处理大规模的数据展示和交互。
以下是我对Swift中UICollectionView的用法的深度和广度的评估:一、基础概念1. UICollectionView是iOS中用来展示可滚动多列数据的一种View组件。
2. UICollectionView需要通过UICollectionViewFlowLayout进行布局,以确定每个Item的位置和大小。
3. UICollectionViewDataSource用于告诉UICollectionView有多少个Section和每个Section有多少个Item。
4. UICollectionViewDelegate用于处理用户的交互事件,比如选择、滚动等。
二、使用方法1. 创建UICollectionView和UICollectionViewFlowLayout在Swift中,我们可以使用Storyboard或者纯代码方式创建UICollectionView,并且配置对应的UICollectionViewFlowLayout。
在创建UICollectionView时,需要设置其dataSource和delegate。
2. 实现UICollectionViewDataSource和UICollectionViewDelegate我们需要在ViewController中实现UICollectionViewDataSource和UICollectionViewDelegate协议,来提供UICollectionView所需的数据和处理用户的交互事件。
3. 自定义UICollectionViewCell通常我们会自定义UICollectionViewCell来展示数据,这样能够更好地控制展示的样式和交互。
简书swift collectionview 用法全文共四篇示例,供读者参考第一篇示例:简书(swift)是一款基于Swift语言开发的开源UI组件库,可以帮助开发者快速构建iOS应用。
其中的CollectionView是一种非常常用的界面元素,用于展示多个数据项,并且支持滚动、点击等交互操作。
本文将介绍如何在简书(swift)中使用CollectionView,并且详细解析CollectionView的各种用法。
一、CollectionView的基本用法1. 创建CollectionView在简书(swift)中创建一个CollectionView非常简单,只需要在Xcode中新建一个CollectionView控件即可。
在Storyboard中拖拽一个CollectionView控件到视图中,然后设置其约束以及数据源和代理,即可完成基本的搭建。
3. 自定义CellCollectionView中的每个数据项都对应一个Cell,开发者可以自定义Cell的外观和布局。
在简书(swift)中,可以通过自定义Cell类并在数据源方法中返回自定义的Cell对象来实现。
4. 加载数据一般情况下,CollectionView会显示一组数据项,开发者需要通过数据源方法来加载这些数据。
可以从本地文件或者网络接口获取数据,并在数据源方法中返回给CollectionView。
二、CollectionView的进阶用法1. 多种布局样式CollectionView支持多种布局样式,比如流式布局、网格布局等。
在简书(swift)中,可以通过设置CollectionView的布局对象来实现不同的布局效果。
2. 添加动画效果为了提升用户体验,开发者可以在CollectionView中添加各种动画效果。
比如Cell的进入、离开动画,以及滚动动画等。
在简书(swift)中,可以通过CollectionView的代理方法或者自定义动画对象来实现这些动画效果。
uicollectionview section的间距-回复UICollectionView是iOS中常用的控件,它可以按照行或列的方式展示一组数据项。
在UICollectionView中,我们可以通过设置section的间距来调整不同section之间的距离,从而达到更好的展示效果。
第一步:了解UICollectionView的基本概念和用法在开始讨论UICollectionView的section间距之前,我们先来了解一下UICollectionView的基本概念和用法。
UICollectionView是一种用于展示多个单元格的高度自定义的容器视图。
与UITableView类似,UICollectionView也基于UICollectionViewLayout进行布局,通过UICollectionViewDataSource 和UICollectionViewDelegate协议来协助数据的展示和交互。
在UICollectionView中,单元格被分组为section,并按照某种方向(水平或垂直)依次排列。
每个section中包含一个或多个单元格,可以自定义每个单元格的布局和样式。
第二步:理解section的间距在默认情况下,UICollectionView中的section之间是紧密排列的,没有间隔。
然而,在某些情况下,我们可能希望在section之间增加一定的间距,以便更好地区分不同的数据集合。
section的间距主要指的是不同section之间的距离,可以通过设置UICollectionViewFlowLayout的属性来进行调整。
第三步:通过UICollectionViewFlowLayout设置section间距UICollectionViewFlowLayout是iOS提供的一种用于管理UICollectionView布局的默认布局类。
通过调整其属性,我们可以实现不同的布局效果。
黑马程序员:IOS面试宝典之UITableView与UICollectionView 1.UITableView的重用机制?(或者如何在一个view上显示多个tableView,tableView要求不同的数据源以及不同的样式(要求自定义cell), 如何组织各个tableView的delegate和dataSource?请说说实现思路?)查看UITableView头文件,会找到NSMutableArray*visiableCells,和NSMutableArray*reusableTableCells两个结构。
visiableCells内保存当前显示的cells,reusableTableCells保存可重用的cells。
TableView显示之初,reusableTableCells为空,那么tableView dequeueReusableCellWithIdentifier:CellIdentifier返回nil。
开始的cell都是通过[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] 来创建,而且cellForRowAtIndexPath只是调用最大显示cell数的次数。
比如:有100条数据,iPhone一屏最多显示10个cell。
程序最开始显示TableView的情况是:1. 用[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:CellIdentifier] 创建10次cell,并给cell指定同样的重用标识(当然,可以为不同显示类型的cell指定不同的标识)。
并且10个cell全部都加入到visiableCells数组,reusableTableCells为空。
iOS 开发tips-UITableView 、UICollectionView ⾏⾼尺⼨⾃适应我们都知道UITableView 从iOS 8开始实现⾏⾼的⾃适应相对⽐较简单,⾸先必须设置estimatedRowHeight 给出预估⾼度,设置rowHeight 为UITableViewAutomaticDimension (注意:如果不修改rowHeight 默认就是UITableViewAutomaticDimension ),对于这两个参数除了直接修改tableview 对应的属性之外仍然⽀持使⽤对应的代理⽅法设置。
最后只要在UITableViewCell 中设置contentView 的约束即可。
由于UITableViewCell 的宽度等同于UITableView 因此约束的设置事实上只是为了⾃动计算⾼度。
通常的做法就是设置contentView 的top 和bottom 约束,⽽后其内部⼦视图可以提供intrinsicContentSize (例如UIButtonUILabel 默认就已经提供)或者已经有明确的height 约束。
这样⼀来就可以做到⼦控件确定了⾃⾝⾼度,⽽contentView ⼦控件⼜设置了和contentView 相关的bottom 约束来反向计算出UITableViewCell 的实际⾼度。
下⾯仍然以前⾯⽂章的⾃定义Cell 举例,相⽐之前⼤量的运算⽽⾔Self-Sizing Cells 可以说简化了很多。
除了设置estimatedRowHeight 外最重要的就是添加相关Autolayout 约束。
由于头像⾼度已经固定,内容⾼度可以通过固有⾼度⾃动计算,⽽⼆者的间隔和top 、bottom 约束已经固定,从⽽Self-Sizing Cells 可以⾃动计算出Cell 的⾼度。
⾼度计算约束关系:Cell 布局代码:import UIKitimport SnapKitclass StatusTableViewCell: UITableViewCell {// MARK: - 公共属性var status:Status! {didSet {self.avatarImageView.image = UIImage(named: status.profileImageUrl)erNameLabel.text = erNameself.mtypeImageView.image = UIImage(named: status.mbtype)self.createdAtLabel.text = status.createdAtself.sourceLabel.text = status.sourceself.contentLabel.text = status.text}}// MARK: - ⽣命周期及⽅法覆盖override func awakeFromNib() {super.awakeFromNib()}override init(style: UITableViewCellStyle, reuseIdentifier: String?) {super.init(style: style, reuseIdentifier: reuseIdentifier)self.setup()}required init?(coder aDecoder: NSCoder) {super.init(coder: aDecoder)}override func setSelected(_ selected: Bool, animated: Bool) {}// MARK: - 私有⽅法private func setup() {self.contentView.addSubview(self.avatarImageView) self.contentView.addSubview(erNameLabel)UITableViewself.contentView.addSubview(erNameLabel)self.contentView.addSubview(self.mtypeImageView)self.contentView.addSubview(self.createdAtLabel)self.contentView.addSubview(self.sourceLabel)self.contentView.addSubview(self.contentLabel)self.avatarImageView.snp.makeConstraints { (make) inmake.top.left.equalTo(10.0)make.size.equalTo(CGSize(width: 40.0, height: 40.0))}erNameLabel.snp.makeConstraints { (make) inmake.top.equalTo(self.avatarImageView.snp.top)make.left.equalTo(self.avatarImageView.snp.right).offset(8.0)}self.mtypeImageView.snp.makeConstraints { (make) inmake.top.equalTo(erNameLabel.snp.top)make.left.equalTo(erNameLabel.snp.right).offset(8.0)make.size.equalTo(CGSize(width: 14.0, height: 14.0))}self.createdAtLabel.snp.makeConstraints { (make) inmake.left.equalTo(erNameLabel.snp.left)make.bottom.equalTo(self.avatarImageView.snp.bottom)}self.sourceLabel.snp.makeConstraints { (make) inmake.left.equalTo(self.createdAtLabel.snp.right).offset(10.0)make.bottom.equalTo(self.createdAtLabel.snp.bottom)make.right.lessThanOrEqualTo(-8.0)}self.contentLabel.snp.makeConstraints { (make) inmake.top.equalTo(self.avatarImageView.snp.bottom).offset(8.0)make.left.equalTo(self.avatarImageView.snp.left)make.right.equalTo(-8.0)make.bottom.equalTo(-10.0) // 注意此处必须设置,否则contentView⽆法⾃适应⾼度}}// MARK: - 私有属性private lazy var avatarImageView:UIImageView = {let temp = UIImageView()return temp}()private lazy var mtypeImageView:UIImageView = {let temp = UIImageView()return temp}()private lazy var userNameLabel:UILabel = {let temp = UILabel()temp.textColor = UIColor(red: 50.0/255.0, green: 50.0/255.0, blue: 50.0/255.0, alpha: 1.0)temp.font = UIFont.systemFont(ofSize: 14.0)return temp}()private lazy var createdAtLabel:UILabel = {let temp = UILabel()temp.textColor = UIColor(red: 120.0/255.0, green: 120.0/255.0, blue: 120.0/255.0, alpha: 1.0) temp.font = UIFont.systemFont(ofSize: 12.0)return temp}()private lazy var sourceLabel:UILabel = {let temp = UILabel()temp.textColor = UIColor(red: 120.0/255.0, green: 120.0/255.0, blue: 120.0/255.0, alpha: 1.0) temp.font = UIFont.systemFont(ofSize: 12.0)return temp}()}()private lazy var contentLabel:UILabel = {let temp = UILabel()temp.textColor = UIColor(red: 50.0/255.0, green: 50.0/255.0, blue: 50.0/255.0, alpha: 1.0)temp.font = UIFont.systemFont(ofSize: 14.0)temp.numberOfLines = 0return temp}()}最终效果:⽆论是UITableView 还是后⾯的UICollectionview ,Self-Sizing Cells 的概念均是从iOS 8开始提出的。
IOS6新特性之集合视图UICollectionView介绍
起首,CollectionView包括以下几个部门:
1、View元素部门
2、数据模子和交互部门
3、contents表现部门
4、View样式部门<下次先容>
一、View元素部门
IOS6SDK中提供了这个全新UI的属性和要领等。
查察之后,我们可以总结出CollectionView中包括了以下几个要害字部门:
UICollectionView<根基的UI部门>
UICollectionViewDataSource<数据源部门,很想UITableView>
UICollectionViewLayoutAttributes<问题部门>
发明一个题目,UICollectionView很想UITableView,就像亲兄弟一样,呵呵~~
1、CollectionView照片墙Demo最终结果展示
貌似有点像书架,不外这只是感性的熟悉罢了,接下类我们举办分解。
2、通过上图,我们可以获得这样的几个部门:
Cells单位格
SupplementaryViews增补的view部门,着实类似于UITableView的header 和footer部门
DecorationViews
起首看Cells部门
可以看到Cells部门就是我们最终必要表现的图片部门,也就是每一张图。
SupplementaryViews如下图右边白色的笔墨部门
DecorationViews如下图
最终,三个元素,就组成了照片墙,下面是元素组成图
二、数据模子和交互部门
1、数据模子<UICollectionViewDataSource>
UICollectionViewDataSource就是一个署理,为collectionView提供数据,同UITableView类似,它可以界说有几多个section、一个section内里有几多个item、提供cell的supplementaryview的配置。
要领先容:
<1>numberOfSectionsInCollectionView,即返回几多个section
在上图中只必要返回2个。
<2>collectionView:numberOfItemsInSection:
在每个section中有几多个items。
这时辰我们就必要举办section的判定了,上图中第一个section返回4个,第二个section返回5个。
<3>collectionView:cellForItemAtIndexPath
在每个item上面应该表现什么内容。
譬喻在上图中的section0item0位置表现下图:
<4>Cell和View的重用
和UITableView一样,CollectionView也有重用机制,也有ReuseQueue。
只有当当前表现view的部门,数据才加载表现,其他部门都被放在了重用行列内里了。
在IOS6中体系老是会为我们初始化了Cell,在行使中必要举办Cell类的注册:
注册要领有:
-(void)registerClass:forCellWithReuseIdentifier:-(void)registerCl ass:forSupplementaryViewOfKind:withReuseIdentifier:-(void)registerNib :forCellWithReuseIdentifier:-(void)registerNib:forSupplementaryViewOf Kind:withReuseIdentifier:
从行列中取出一个Cell,详细要领如下:
-(id)dequeueReusableCellWithReuseIdentifier:forIndexPath:-(id)deq ueueReusableSupplementaryViewOfKind:withReuseIdentifier:forIndexPath: 下面我们通过现实的代码,来演示详细怎样举办Cell的重用
第一步:在collectionview中举办配置(Cell类的注册)
//Incollectionviewsetup...[collectionViewregisterClass:[MyCellcla ss]forCellWithR euseIdentifier:@”MY_CELL_ID”]
第二步:在下面的函数中,从行列中取出一个cell即可。
而且再也不消对cell举办空值判定,以做特另外初始化操纵。
Cell的统统初始化事变都由体系为我们做好了。
我们只必要对cell举办一些赋值等操纵即可。
-(UICollectionView*)collectionView:(UICollectionView*)cvcellForIt emAtIndexPath:(NSIndexPath*)indexPath{MyCell*cell=[cvdequeueReusableC ellWithReuseIdentifier:@”MY_CELL_ID”];if(!cell){//Well,nothingreall y.Neveragain}//Configurethecell'scontentcell.imageView.image=...retur ncell;}2、交互部门
UICollectionViewDelegate的首要成果:
节制cell的高亮
节制cell的选择
在cell上支持菜单操纵,如下图
<1>打点cell的触摸高亮结果collectionView:shouldHighlightItemAtIndexPath:collectionView:didHighl ightItemAtIndexPath:collectionView:didUnhighlightItemAtIndexPath:
<2>打点cell的选择结果collectionView:shouldSelectItemAtIndexPath:collectionView:didSelectIt emAtIndexPath:collectionView:shouldDeselectItemAtIndexPath:collection View:didDeselectItemAtIndexPath:
三、内容的表现UICollectionViewCell
CollectionView跟踪cell的选择和高亮,通过配置cell的highlight和
selection属性(包括子视图)
假如举办了相干设置,这可以切换backgroundview和selectedbackgroundview
下面就按照从最底层到最上层的次序展示其内容:
下图是UICollectionView相干的类图,从图中我们可以看到
1.UICollectionView担任自UIScrollView,
2.尊循UICollectionViewDelegate和UICollectionViewDataSource两个协议
3.打点UICollectionViewCell。