title: iOS-单独使用UICollectionCellview视图
date: 2016-06-30 16:15:07
categories:
- Code
- iOS
tags: - UICollectionCell
单独使用collectionCell视图
偶然间在别人工程中看到的,方法很简单下面就让我来给大家说下 简单实现使用collectionCell 创建等同于view的视图
用法
#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
#define floatByScreenWidth(a) ((a)/320.0)*SCREEN_WIDTH
1.自定义collectionCell 添加你需要的属性
(比如添加一个图片 后者标题) 这里不再说
2.自定义一个view 声明一个方法
- (void)setView; // 声明一个方法
- (void)setView { // 实现方法
for (int i = 0; i < 8; i++) { // 需要创建几个视图
// 读取cell 属性复制 添加点击事件 计算坐标
MyCollectionCell *cell = [[[NSBundle mainBundle]loadNibNamed:@"MyCollectionCell" owner:self options:nil]lastObject];
cell.backgroundColor = [UIColor colorWithRed:arc4random()%255/255.0 green:arc4random()%255/255.0 blue:arc4random()%255/255.0 alpha:arc4random()%255/255.0];
cell.nametitle.text = [NSString stringWithFormat:@"第%dcell",i];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]init];
[tap addTarget:self action:@selector(ClickVideoSites:)];
cell.tag = i+1;
tap.view.tag = i+1;
[cell addGestureRecognizer:tap];
int x = i/8;
if (x<4) {
cell.frame = [self setFrameBynum:i andPage:x];
}else{
cell.frame = [self setFrameBynum:i andPage:x];
}
[self addSubview:cell]; // self 即是自定义view视图
}
}
}
//布局cell的位置
- (CGRect)setFrameBynum:(int)num andPage:(int)page
{
CGFloat length = floatByScreenWidth(74);
CGFloat height = length/74*85;
CGFloat width = (SCREEN_WIDTH-4*length)/5;
if (num < 4) {
return CGRectMake(width + page * SCREEN_WIDTH + (length+width)*num, 0, length, height);
}
else
return CGRectMake(width + page * SCREEN_WIDTH + (length+width)*(num-4),height + 10, length, height);
}
3.Controller里面使用
MyView * _myView = [[MyView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
[_myView setView];
[self.view addSubview:_myView];
class XYNoDataView: UIView {
var nodataView: XYAddressMyFriendNoDataCell?
private func setup() {
self.backgroundColor = #colorLiteral(red: 0.9490196078, green: 0.9607843137, blue: 0.968627451, alpha: 1)
let rect = CGRect(x: 0, y: 68, w: UIScreen.main.bounds.size.width, h: 240)
let nodataView = Bundle.main.loadNibNamed("XYAddressMyFriendNoDataCell", owner: nil, options: nil)?.first as! XYAddressMyFriendNoDataCell
nodataView.frame = rect
self.addSubview(nodataView)
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
}
到这里已经实现自定义collectioncell视图的使用,希望帮到你们,谢谢