构建iPad应用程序时,如何在UICollectionViewCell周围绘制边框?
更多细节:我实现了一个扩展UICollectionViewCell的ProductCell类。现在,我想指定一些花哨的细节,例如边框,阴影等。然而,当尝试使用this here之类的东西时,Xcode告诉我接收器类型'CALayer'是一个前向声明。
答案 0 :(得分:71)
只是为了更多的实施:
#import <QuartzCore/QuartzCore.h>
在你的.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;
}
答案 1 :(得分:19)
更新了Swift 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
,则无需在Swift中导入UIKit
。答案 2 :(得分:7)
您需要包含框架QuartzCore
并将标头导入您的班级:
#import <QuartzCore/QuartzCore.h>
答案 3 :(得分:1)
快捷键4
cell.layer.borderColor = UIColor.black.cgColor
cell.layer.borderWidth = 1
在创建单元格之后,将其添加到数据源方法中
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath)
cell.layer.borderColor = UIColor.black.cgColor
cell.layer.borderWidth = 1
}
答案 4 :(得分:0)
我认为最好将此配置添加到您的自定义单元实现中,而不是在数据源委托方法中。
cell.layer.borderColor = UIColor.black.cgColor
cell.layer.borderWidth = 1
cell.layer.cornerRadius = 8 // optional