UICollectionViewCell边框/阴影

its*_*e69 31 objective-c uicollectionview uicollectionviewcell

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

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

Jam*_*son 72

只是为了更多的实现:

#import <QuartzCore/QuartzCore.h>
Run Code Online (Sandbox Code Playgroud)

在你的.m

确保你的类实现

- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath; 
Run Code Online (Sandbox Code Playgroud)

因为这是设置单元格的地方.

然后您可以更改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;
}
Run Code Online (Sandbox Code Playgroud)


Sur*_*gch 20

迅速

针对Swift 3进行了更新

假设您使用所需方法设置了Collection View,您只需编写几行代码即可添加边框.

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
}
Run Code Online (Sandbox Code Playgroud)

笔记

  • QuartzCore如果您已导入,则无需在Swift中导入UIKit.
  • 如果您还想添加阴影,请参阅此答案.


Mun*_*ndi 7

您需要包含框架QuartzCore并将标头导入到您的类中:

#import <QuartzCore/QuartzCore.h>
Run Code Online (Sandbox Code Playgroud)