我正在寻找一个指南或教程,它将向我展示如何仅使用代码来设置简单的UICollectionView。
我正在仔细阅读Apples网站上的文档,并且也在使用参考手册。
但是我真的会从一个简单的指南中受益,该指南可以向我展示如何设置UICollectionView,而不必使用Storyboards或XIB / NIB文件-但是不幸的是,当我搜索时,我所能找到的只是带有Storyboard的教程。
Initializing a Collection View
,您是否从那里使用初始化程序?
我正在寻找一个指南或教程,它将向我展示如何仅使用代码来设置简单的UICollectionView。
我正在仔细阅读Apples网站上的文档,并且也在使用参考手册。
但是我真的会从一个简单的指南中受益,该指南可以向我展示如何设置UICollectionView,而不必使用Storyboards或XIB / NIB文件-但是不幸的是,当我搜索时,我所能找到的只是带有Storyboard的教程。
Initializing a Collection View
,您是否从那里使用初始化程序?
Answers:
头文件:-
@interface ViewController : UIViewController<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
{
UICollectionView *_collectionView;
}
实施文件:-
- (void)viewDidLoad
{
[super viewDidLoad];
self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init];
_collectionView=[[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
[_collectionView setDataSource:self];
[_collectionView setDelegate:self];
[_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellIdentifier"];
[_collectionView setBackgroundColor:[UIColor redColor]];
[self.view addSubview:_collectionView];
// Do any additional setup after loading the view, typically from a nib.
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return 15;
}
// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
cell.backgroundColor=[UIColor greenColor];
return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(50, 50);
}
输出-
@property (strong, nonatomic) UICollectionView *collectionView;
UICollectionViewCell
确实不想注册UICollectionViewCell
,而是希望对其进行子类化,请在initWithFrame
方法中对单元格进行配置,然后使用单元格标识符注册此子类不是UICollectionViewCell
。
_collectionView=[[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
对于swift4用户:-
class TwoViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UICollectionViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: flowLayout)
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "collectionCell")
collectionView.delegate = self
collectionView.dataSource = self
collectionView.backgroundColor = UIColor.cyan
self.view.addSubview(collectionView)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 20
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
var cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath as IndexPath)
cell.backgroundColor = UIColor.green
return cell
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSize(width: 50, height: 50)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
}
}
对于Swift 2.0
而不是实现绘制所需的方法CollectionViewCells
:
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
{
return CGSizeMake(50, 50);
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets
{
return UIEdgeInsetsMake(5, 5, 5, 5); //top,left,bottom,right
}
用 UICollectionViewFlowLayout
func createCollectionView() {
let flowLayout = UICollectionViewFlowLayout()
// Now setup the flowLayout required for drawing the cells
let space = 5.0 as CGFloat
// Set view cell size
flowLayout.itemSize = CGSizeMake(50, 50)
// Set left and right margins
flowLayout.minimumInteritemSpacing = space
// Set top and bottom margins
flowLayout.minimumLineSpacing = space
// Finally create the CollectionView
let collectionView = UICollectionView(frame: CGRectMake(10, 10, 300, 400), collectionViewLayout: flowLayout)
// Then setup delegates, background color etc.
collectionView?.dataSource = self
collectionView?.delegate = self
collectionView?.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "cellID")
collectionView?.backgroundColor = UIColor.whiteColor()
self.view.addSubview(collectionView!)
}
然后UICollectionViewDataSource
根据需要实现方法:
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 20;
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
var cell:UICollectionViewCell=collectionView.dequeueReusableCellWithReuseIdentifier("collectionCell", forIndexPath: indexPath) as UICollectionViewCell;
cell.backgroundColor = UIColor.greenColor();
return cell;
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
迅捷3
class TwoViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UICollectionViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let flowLayout = UICollectionViewFlowLayout()
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: flowLayout)
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "collectionCell")
collectionView.delegate = self
collectionView.dataSource = self
collectionView.backgroundColor = UIColor.cyan
self.view.addSubview(collectionView)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return 20
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath as IndexPath)
cell.backgroundColor = UIColor.green
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
return CGSize(width: 50, height: 50)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets
{
return UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
}
}
以@Warewolf的答案为基础,下一步是创建自己的自定义单元。
去File -> New -> File -> User Interface -> Empty -> Call
这个笔尖"customNib"
。
在customNib
拖动UICollectionView
单元格时,为其提供重复使用的单元格标识符@"Cell"
。
File -> New -> File -> Cocoa Touch Class -> Class
"CustomCollectionViewCell"
如果命名子类UICollectionViewCell
。
返回自定义笔尖,单击“单元格”,然后创建此自定义类"CustomCollectionViewCell"
。
转到您的viewDidLoad
viewcontroller
,而不是
[_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellIdentifier"];
有
UINib *nib = [UINib nibWithNibName:@"customNib" bundle:nil];
[_collectionView registerNib:nib forCellWithReuseIdentifier:@"Cell"];
另外,更改(更改为新的单元格标识符)
UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
您可以在uicollection视图中处理自定义单元格,请参见以下代码。
- (void)viewDidLoad
{
UINib *nib2 = [UINib nibWithNibName:@"YourCustomCell" bundle:nil];
[CollectionVW registerNib:nib2 forCellWithReuseIdentifier:@"YourCustomCell"];
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
[flowLayout setItemSize:CGSizeMake(200, 230)];
flowLayout.minimumInteritemSpacing = 0;
[flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
[CollectionVW setCollectionViewLayout:flowLayout];
[CollectionVW reloadData];
}
#pragma mark - COLLECTIONVIEW
#pragma mark Collection View CODE
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return Array.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"YourCustomCell";
YourCustomCell *cell = (YourCustomCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
cell.MainIMG.image=[UIImage imageNamed:[Array objectAtIndex:indexPath.row]];
return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
}
#pragma mark Collection view layout things
// Layout: Set cell size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
CGSize mElementSize;
mElementSize=CGSizeMake(kScreenWidth/3.4, 150);
return mElementSize;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
return 5.0;
}
// Layout: Set Edges
- (UIEdgeInsets)collectionView: (UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
if (isIphone5 || isiPhone4)
{
return UIEdgeInsetsMake(15,15,5,15); // top, left, bottom, right
}
else if (isIphone6)
{
return UIEdgeInsetsMake(15,15,5,15); // top, left, bottom, right
}
else if (isIphone6P)
{
return UIEdgeInsetsMake(15,15,5,15); // top, left, bottom, right
}
return UIEdgeInsetsMake(15,15,5,15); // top, left, bottom, right
}
苹果文档:
- (id)initWithFrame:(CGRect)frame
collectionViewLayout:(UICollectionViewLayout *)layoutParameters
以编程方式初始化集合视图对象时,请使用此方法。如果为layout参数指定nil,则必须在屏幕上显示集合视图之前将布局对象分配给collectionViewLayout属性。否则,收藏夹视图将无法在屏幕上显示任何项目。
此方法是指定的初始化程序。
此方法用于初始化UICollectionView
。在这里,您提供框架和UICollectionViewLayout
对象。
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
最后,将UICollectionView
a 添加subview
到您的视图中。
现在,集合视图以编程方式添加。您可以继续学习。
学习愉快!希望对您有帮助。
The layout object to use for organizing items. The collection view stores a strong reference to the specified object. Must not be nil.
#pragma mark -
#pragma mark - UICollectionView Datasource and Delegates
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return Arr_AllCulturalButtler.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *coll=@"FromCulturalbutlerCollectionViewCell";
FromCulturalbutlerCollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:coll forIndexPath:indexPath];
cell.lbl_categoryname.text=[[Arr_AllCulturalButtler objectAtIndex:indexPath.row] Category_name];
cell.lbl_date.text=[[Arr_AllCulturalButtler objectAtIndex:indexPath.row] event_Start_date];
cell.lbl_location.text=[[Arr_AllCulturalButtler objectAtIndex:indexPath.row] Location_name];
[cell.Img_Event setImageWithURL:[APPDELEGATE getURLForMediumSizeImage:[(EventObj *)[Arr_AllCulturalButtler objectAtIndex:indexPath.row] Event_image_name]] placeholderImage:nil usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
cell.button_Bookmark.selected=[[Arr_AllCulturalButtler objectAtIndex:indexPath.row] Event_is_bookmarked];
[cell.button_Bookmark addTarget:self action:@selector(btn_bookmarkClicked:) forControlEvents:UIControlEventTouchUpInside];
cell.button_Bookmark.tag=indexPath.row;
return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
[self performSegueWithIdentifier:SEGUE_CULTURALBUTLER_KULTURELLIS_DETAIL sender:self];
}
// stroy board navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"Overview_Register"])
{
WDRegisterViewController *obj=(WDRegisterViewController *)[segue destinationViewController];
obj.str_Title=@"Edit Profile";
obj.isRegister=NO;
}
}
[self performSegueWithIdentifier:@"Overview_Measure" sender:nil];
UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
WDPeekViewController *Peek = (WDPeekViewController *)[sb instantiateViewControllerWithIdentifier:@"WDPeekViewController"];
[self.navigationController pushViewController:tabBarController animated:YES];
集合视图考试
#import "CollectionViewController.h"
#import "BuyViewController.h"
#import "CollectionViewCell.h"
@interface CollectionViewController ()
{
NSArray *mobiles;
NSArray *costumes;
NSArray *shoes;
NSInteger selectpath;
NSArray *mobilerate;
NSArray *costumerate;
NSArray *shoerate;
}
@end
@implementation CollectionViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = self.receivename;
mobiles = [[NSArray alloc]initWithObjects:@"7.jpg",@"6.jpg",@"5.jpg", nil];
costumes = [[NSArray alloc]initWithObjects:@"shirt.jpg",@"costume2.jpg",@"costume1.jpg", nil];
shoes = [[NSArray alloc]initWithObjects:@"shoe.jpg",@"shoe1.jpg",@"shoe2.jpg", nil];
mobilerate = [[NSArray alloc]initWithObjects:@"10000",@"11000",@"13000",nil];
costumerate = [[NSArray alloc]initWithObjects:@"699",@"999",@"899", nil];
shoerate = [[NSArray alloc]initWithObjects:@"599",@"499",@"300", nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return 3;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellId = @"cell";
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];
UIImageView *collectionImg = (UIImageView *)[cell viewWithTag:100];
if ([self.receivename isEqualToString:@"Mobiles"])
{
collectionImg.image = [UIImage imageNamed:[mobiles objectAtIndex:indexPath.row]];
}
else if ([self.receivename isEqualToString:@"Costumes"])
{
collectionImg.image = [UIImage imageNamed:[costumes objectAtIndex:indexPath.row]];
}
else
{
collectionImg.image = [UIImage imageNamed:[shoes objectAtIndex:indexPath.row]];
}
return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
selectpath = indexPath.row;
[self performSegueWithIdentifier:@"buynow" sender:self];
}
// In a storyboard-based application, you will often want to do a little
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"buynow"])
{
BuyViewController *obj = segue.destinationViewController;
if ([self.receivename isEqualToString:@"Mobiles"])
{
obj.reciveimg = [mobiles objectAtIndex:selectpath];
obj.labelrecive = [mobilerate objectAtIndex:selectpath];
}
else if ([self.receivename isEqualToString:@"Costumes"])
{
obj.reciveimg = [costumes objectAtIndex:selectpath];
obj.labelrecive = [costumerate objectAtIndex:selectpath];
}
else
{
obj.reciveimg = [shoes objectAtIndex:selectpath];
obj.labelrecive = [shoerate objectAtIndex:selectpath];
}
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
}
@end
.h文件
@interface CollectionViewController :
UIViewController<UICollectionViewDelegate,UICollectionViewDataSource>
@property (strong, nonatomic) IBOutlet UICollectionView *collectionView;
@property (strong,nonatomic) NSString *receiveimg;
@property (strong,nonatomic) NSString *receivecostume;
@property (strong,nonatomic)NSString *receivename;
@end
为谁想要创建一个自定义单元格:
CustomCell.h
#import <UIKit/UIKit.h>
@interface HeaderCollectionViewCell : UICollectionViewCell
@property (strong,nonatomic) UIImageView *image;
@end
CustomCell.m
#import "HeaderCollectionViewCell.h"
@implementation HeaderCollectionViewCell
#define IMAGEVIEW_BORDER_LENGTH 5
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self setup];
}
return self;
}
-(void)setup{
_image = [[UIImageView alloc] initWithFrame:(CGRectInset(self.bounds, IMAGEVIEW_BORDER_LENGTH, IMAGEVIEW_BORDER_LENGTH))];
[self addSubview:_image];
}
@end
UIViewController.h
#import <UIKit/UIKit.h>
@interface HomeViewController : UIViewController<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property (strong,nonatomic) UICollectionView *collectionView;
@end
UIViewController.m
#import "HomeViewController.h"
#import "HomeView.h"
#import "HeaderCollectionViewCell.h"
@interface HomeViewController ()
@property (nonatomic) NSString *cellID;
@end
@implementation HomeViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = UIColor.whiteColor;
_cellID = @"id";
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
_collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
[_collectionView registerClass:[HeaderCollectionViewCell class] forCellWithReuseIdentifier:_cellID];
[_collectionView setDataSource:self];
[_collectionView setDelegate:self];
_collectionView.backgroundColor = UIColor.redColor;
[self.view addSubview:_collectionView];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return 4;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
HeaderCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:_cellID forIndexPath:indexPath];
cell.image.image = [UIImage imageNamed:@"premium-icon"];
return cell;
}
-(UITabBarItem*) tabBarItem{
return [[UITabBarItem alloc] initWithTitle:@"Início" image:[UIImage imageNamed:@"home-icon"] tag:0];
}
@end
swift 4 code
//
// ViewController.swift
// coolectionView
//
import UIKit
class ViewController: UIViewController , UICollectionViewDataSource, UICollectionViewDelegate,UICollectionViewDelegateFlowLayout{
@IBOutlet weak var collectionView: UICollectionView!
var items = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.items.count
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
if indexPath.row % 3 != 0
{
return CGSize(width:collectionView.frame.width/2 - 7.5 , height: 100)
}
else
{
return CGSize(width:collectionView.frame.width - 10 , height: 100 )
}
}
// make a cell for each cell index path
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// get a reference to our storyboard cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell1234", for: indexPath as IndexPath) as! CollectionViewCell1234
// Use the outlet in our custom class to get a reference to the UILabel in the cell
cell.lbl1.text = self.items[indexPath.item]
cell.backgroundColor = UIColor.cyan // make cell more visible in our example project
cell.layer.borderColor = UIColor.black.cgColor
cell.layer.borderWidth = 1
cell.layer.cornerRadius = 8
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// handle tap events
print("You selected cell #\(indexPath.item)!")
}
}