2012-10-29 121 views
30

构建iPad应用程序时,如何在UICollectionViewCell周围绘制边框?UICollectionViewCell边框/阴影

更多细节:我实现了一个扩展UICollectionViewCell的类ProductCell。现在,我想分配一些花哨的细节,例如边界,阴影等。但是,当试图使用类似this here的东西时,Xcode告诉我接收器类型'CALayer'是前向声明。

回答

71

只是为了多一点的实现:

#import <QuartzCore/QuartzCore.h> 

在your.m

确保您的班级实施

- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath; 

因为这是单元格的设置。

然后,您可以更改cell.layer.background(仅一次石英进口)

见下

- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath { 
    MyCollectionViewCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"pressieCell" forIndexPath:indexPath]; 
    //other cell setup here 

    cell.layer.borderWidth=1.0f; 
    cell.layer.borderColor=[UIColor blueColor].CGColor; 

    return cell; 
} 
7

您需要包括框架QuartzCore并导入到头类:

#import <QuartzCore/QuartzCore.h> 
11

斯威夫特

更新了斯威夫特3

假设你有你的Collection View set up with the required methods ,你可以只写几行代码来添加边框。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MyCollectionViewCell 
    cell.myLabel.text = self.items[indexPath.item] 
    cell.backgroundColor = UIColor.cyan 

    // add a border 
    cell.layer.borderColor = UIColor.black.cgColor 
    cell.layer.borderWidth = 1 
    cell.layer.cornerRadius = 8 // optional 

    return cell 
} 

注意

  • 没有必要在斯威夫特导入QuartzCore如果您已经导入UIKit
  • 如果您还想添加阴影,请参阅this answer